2013-09-25 115 views
0

我試圖做這樣的事情:條件選擇在SQL語句

SELECT UserID from Users as user 
    INNER JOIN UserStatus as userStatus on u.UserID = us.UserID 
WHERE 
    --user.IsActive = 1 
    --if user.IsActive = 0 
     --userStatus.DeactivatedDate > @StartDate 
     --userStatus.DeactivatedDate < @EndDate 

所以一般我想要一個查詢,讓我所有的結果,其值在where語句相匹配,而不必忽略所有這些結果那不。有點像維恩圖,圓圈左側,中間填充。對於我已經展示的例子,我希望所有當前活動的用戶以及沒有活動但在給定時間內活動的用戶框架(例如,如果我想在一個月內的任何一點活躍的用戶總數)。

我試着做這樣的事情

SELECT UserID from Users as user 
    INNER JOIN UserStatus as userStatus on u.UserID = us.UserID 
WHERE 
    Case user.IsActive = 1 

但是,這顯然是不正確的語法。我也需要把它翻譯成LINQ,所以這方面的資源也是有益的。

回答

3
SELECT UserID from Users as user 
    INNER JOIN UserStatus as userStatus on u.UserID = us.UserID 
WHERE 
    user.IsActive = 1 OR us.DeactvatedDate BETWEEN '2012-08-13' AND '2013-08-13' 

,如果您有任何關於當用戶得到decativated日期的任何條目這將做的工作。

在LINQ

var UID= from u in Users 
     from s in UserStatus 
     where u.UserID == s.UserID || (s.DeactivatedDate >= @StartDate &&   
     s.DeactivatedDate <= @endDate) 
     select u.userID  
+3

呵呵@'decavitated',不管這意味着,這聽起來致命的;) – Khan

+1

抱歉錯字!包含LINQ的 –

+2

+1 – Khan

4

我相信這會給你你正在尋找的結果是:

SELECT UserID 
FROM Users U 
JOIN UserStatus US 
    ON U.UserID = US.UserID 
WHERE 
     U.IsActive = 1 
     OR (
       U.IsActive = 0 
      AND US.DeactivatedDate > @StartDate 
      AND US.DeactivatedDate < @EndDate 
     )