2015-06-27 69 views
2

我想要檢索DaysVisted在兩個值之間的行,例如,如果@days是90,則獲取DaysVisited在90到60之間的記錄,如果@days是60,則獲取DaysVisited之間的記錄60和30sql server多案例where條款

下面的查詢是不給我正確的記錄:

declare @days int 
set @days = 60 
select * from table where 
DaysVisited >= 
CASE     
    when (@days = 90) then 
    when (@days = 60) then @days  
    when (@days = 0) then 0 
END 

我想是這樣的:

declare @days int 
set @days = 60 
select * from table where 

CASE     
    when (@days = 90) then DaysVisited >= 90 and DaysVisited <= 60 
    when (@days = 60) then DaysVisited >= 60 and DaysVisited <= 30 
    when (@days = 0) then 0 
END 
+0

所以它只是始終是天與日 - 30? –

+0

不總是,天也可以爲零,這些可以改變 – Sami

+0

只需添加第二個變量,並在那裏放第二個限制? –

回答

3

您的邏輯是不可能的,一列不能同時在60以下和90以上。試試這個:

DECLARE @days int = 60 

SELECT * 
FROM 
    yourtable 
WHERE 
    DaysVisited between 
    case when @days < 30 then 0 else @days-30 end and @days 
+0

如果用戶選擇90,那麼我想要獲得daysVisited超過90的行,如果用戶選擇60,則在60和90之間,如果零則記錄所有記錄。 – Sami

1
DECLARE @days int = 60; 
DECLARE @MaxDay INT; 
SELECT @MaxDay = MAX(DaysVisited) FROM YourTable; 
SELECT * 
FROM YourTable 
WHERE DaysVisited BETWEEN @days AND 
     CASE 
      WHEN @days=60 THEN 90 
      ELSE @MaxDay 
     END