2014-04-13 138 views
1

這是我的表格。SQL Server中的CASE和GROUP BY

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 

對於每個月份,我需要選擇卷列中前兩個連續零之前的所有行,該列按價格按降序排列。例如以下是我想獲得:

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 

任何建議如何通過一個月的分組做。

+0

您的餐桌是如何訂購的?你如何定義「*連續*」?請不要在你的[其他問題](http://stackoverflow.com/questions/23036457/sql-query-to-choose-row-before-two-consecutive-true-values?lq=1)你有行排序按'價格'。現在是用「價格降月」來表示嗎? –

+0

先按月排序(無所謂順序),然​​後按價格按降序排列。 – user1700890

+1

按月添加分區。請參閱http://technet.microsoft.com/en-us/library/ms189461.aspx –

回答

3

你快到了。您所需要的只是將PARTITION BY month添加到OVER條款中。

這是SQL Fiddl e。

+0

非常感謝! SQL小提琴真棒! – user1700890