Return the Last Month in Quarter Group

时间:2016-11-09 08:17:56

标签: sql-server

My data looks like the following:

*Quarter|Month*  
Q1 2013|Jan 2013     
Q1 2013|Feb 2013  
**Q1 2013|Mar 2013**  
Q2 2013|Apr 2013  
Q2 2013|May 2013  
**Q2 2013|Jun 2013**  
Q3 2013|Jul 2013  
**Q3 2013|Aug 2013**

I want to write a sql query that returns the last month of each quarter, something like the following:

*Month*  
Mar 2013  
Jun 2013  
Aug 2013

I have used the following query to get a little bit further:

*SELECT MONT_KEY, ROW_NUMBER() OVER (PARTITION BY QURT_KEY ORDER BY MONT_KEY) RANKBYQURT FROM ZQUARTERMONTH;*

   MONT_KEY  |  RANKBYQURT  
    Jan 2013  |      1  
    Feb 2013  |      2  
    **Mar 2013  |      3**  
    Apr 2013  |      1  
    May 2013  |      2  
    **Jun 2013  |      3**  
    Jul 2013  |      1  
    **Aug 2013  |      2**  

Now, how do I display only the month with highest rank in each group? Still working....

Best Regards

1 个答案:

答案 0 :(得分:0)

试试这个:

;WITH T as 
(
SELECT Quarter,Month, dense_rank() 
    OVER (PARTITION BY Quarter ORDER BY Year(Month),month(Month) DESC) as Rank FROM @table 
)
SELECT * from T WHERE rank=1