2015-06-27 68 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