简体   繁体   English

需要在SQL Server 2012中打印最高年份和最高季度

[英]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 我尝试了很多连接,最大条件,我似乎得到了他们两个的第4和第4季:(谢谢

Use a window function like ROW_NUMBER in a common-table-expression: 在common-table-expression中使用类似ROW_NUMBER窗口函数

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 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). 即使存在关联(具有相同的最高年份+季度的城市计划), ROW_NUMBER每组仅返回一行。 If you then want to show all highest you can replace ROW_NUMBER with DENSE_RANK . 如果您想要显示所有最高,则可以使用DENSE_RANK替换ROW_NUMBER

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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