首页 > 解决方案 > 取消率最高的输出月份

问题描述

我可以使用以下查询获取自 2018 年以来每个月取消会员的数量 -

SELECT DATEPART(YEAR, Cancel) [Year],
DATEPART(Month, Cancel) [Month], COUNT(1) [Count]
FROM Subscription
where DATEPART(YEAR, Cancel) >= 2018
GROUP BY DATEPART(year, Cancel),DATEPART(Month, Cancel)
ORDER BY 1,2

输出是

Year    Month    Count
2018    1        6416775
2018    2        458171
2018    3        29963575
2018    4        65393505

如何修改此查询,使其仅显示取消次数最多的月份?

更新

这是我想要的输出。每一年都应该有最高的Count输出值。

Year    Month    Count
2018    4        65393505
2019    2        458171

输出 2018 年的第 4 个月,因为它与前 4 个月相比具有最高值。

标签: sqlsql-server

解决方案


使用order by count desc并选择第一条记录top 1可以获得所需的输出:

SELECT TOP 1 DATEPART(YEAR, Cancel) [Year],
DATEPART(Month, Cancel) [Month], COUNT(1) [Count]
FROM Subscription
where DATEPART(YEAR, Cancel) >= 2018
GROUP BY DATEPART(year, Cancel),DATEPART(Month, Cancel)
ORDER BY Count DESC

推荐阅读