在使用where子句的情况下使用T Sql Case

时间:2012-08-24 09:20:06

标签: sql-server case where

尝试使用WHERE BETWEEN执行CASE WHEN

SET @Qtr1 = datepart(MONTH,@dt1)
select 
SUM(QtyInvoiced) as QtrCase
,CustName
,Town
,Rep
from SalesSumNew 
where
FinMonth between
case when @Qtr1 between '1' and '3' THEN '10' and '12'
,case when @Qtr1 between '4' and '6' THEN '1' and '3'
,case when @Qtr1 between '7' and '9' THEN '4' and '6'
,case when @Qtr1 between '10' and '12' THEN '7' and '9'
end
group by CustName, Town, Rep
order by Town

导致错误:

  

Msg 156,Level 15,State 1,Line 57
  关键字'和'附近的语法不正确。

1 个答案:

答案 0 :(得分:3)

你做不到。

尝试使用maths和mod计算范围:类似......

where FinMonth between 
((((2+@qtr1)/3)+2)*3)%12+1,
and
((((2+@qtr1)/3)+2)*3+2)%12+1

如果你的FinMonth真的是一个字符串字段,那么'10','11','12'都在'1'和'3'之间