我想检索DaysVisted在两个值之间的行,例如,如果@days是90,则获取DaysVisited在90到60之间的记录,如果@days是60,则获取DaysVisited在60到30之间的记录。
以下查询未给我正确的记录:
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 :(得分: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
答案 1 :(得分: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