SQL Server中的CASE和GROUP BY

时间:2014-04-13 01:43:59

标签: sql sql-server group-by case

这是我的桌子。

Price   Volume  Month
--------------------------
600    60   April
500    50   April
450    0    April
400    0    April
300    40   April
95     0    April
200    40   March
100    40   March
90     0    March
80     0    March
70     10   March
60     0    March

对于每个月,我需要选择Volume列中前两个连续零之前的所有行,该列按价格按降序排序。例如这是我想得到的:

Price   Volume  Month   rn
--------------------------------
600      60     April   0
500      50     April   0
200      40     March   0
100      40     March   0

我知道如何在没有按月分组的情况下完成它(感谢stackoverflow.com link)。

这是代码:

with 
flagged as (
  select price, 
     volume,
     case 
       when volume + lead(volume) over (order by price desc) = 0 then 1
       else 0
     end as rn, month
  from [AnalysisDatabase].[dbo].[tblLagExample]),
 counted as (
 select price, 
     volume, 
     sum(rn) over (order by price desc) as cn ,-- this is running sum
     rn, month
  from flagged)

select price, volume, cn, month, rn
from counted
 where cn = 0 and rn = 0
 order by price desc

有关如何按月分组的建议。

1 个答案:

答案 0 :(得分:3)

你快到了。您只需要在PARTITION BY month条款中添加OVER

这是SQL Fiddl e。