简体   繁体   中英

Need to print highest year and their highest quarter in SQL Server 2012

I have a requirement to print the corresponding highest year and highest quarter for a given column.

Input is in a table:

cityprogram          year          quarter
===========          ====          =======
Abc                  1998             1
Abc                  1999             4
Abc                  1999             4
Abc                  1998             3
xyz                  1998             4
xyz                  1998             1
xyz                  2000             3

It should print

Abc                 1999             4
xyz                 2000             3

I tried many joins, max conditions, I seem to get quarter 4 and 4 for both of them :( thanks

Use a window function like ROW_NUMBER in a common-table-expression:

WITH CTE AS(
     SELECT [cityprogram], [year], [quarter],
            RN = ROW_NUMBER() OVER (
                   PARTITION BY [cityprogram]
                   ORDER BY [year] DESC, [quarter] DESC)
     FROM dbo.TableName 
)
SELECT [cityprogram], [year], [quarter]
FROM CTE
WHERE RN = 1

DEMO

CITYPROGRAM     YEAR    QUARTER
Abc             1999      4
xyz             2000      3

ROW_NUMBER returns only one row per group even if there are ties(cityprograms with the same highest year+quarter). If you then want to show all highest you can replace ROW_NUMBER with DENSE_RANK .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM