2012-08-24 40 views
1

试图做一个WHERE BETWEENCASE WHEN:错误牛逼的Sql案例的情况下,使用之间时where子句

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
Incorrect syntax near the keyword 'and'.

+0

您收到了什么错误? –

+0

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

回答

3

你不能做到这一点。

尝试用计算数学和MOD的范围:像...

where FinMonth between 
(((([email protected])/3)+2)*3)%12+1, 
and 
(((([email protected])/3)+2)*3+2)%12+1 

如果您FinMonth确实是一个字符串字段,那么“10”,“11”,“12”之间的所有'1'和'3'

+0

+1整洁的解决方案:) –