如何查看 table 中最高值的 COUNT 结果,而不是 sql 中的整个 table

How do I see the COUNT results for only the top values in the table and not the entire table in sql

我正在 SSMS18 中为我的水电费账单创建一个数据库,我正在尝试检索账单最高的前 10 个月中特定月份的出现次数。如何限制 COUNT 功能只计算最上面的行数?

Table设计

CREATE TABLE Electric (
                        [date] date NOT NULL, 
                        electric_bill_amount smallmoney);

我可以通过添加WHERE语句来限制结果

SELECT DISTINCT          DATENAME(MONTH, [date]) AS MONTH,
                         COUNT(DATENAME(MONTH, [date])) AS [Frequency]
FROM Electric
WHERE electric_bill_amount > 104
GROUP BY DATENAME(MONTH, [date])
ORDER BY [Frequency] DESC

但我希望我的查询更加动态,因此只让计数语句使用具有前 10 个最高值的月份。

结果应该是这样的

August 3
September 3
July 2
January 1
December 1
  1. 我猜你正在使用 SQL 服务器,而不是 MySQL。
  2. 只是为了说明你想获得前 10 个最高的电费金额,看看它们是否都在哪个月。
  3. 测试于 dbfiddle
SELECT         DATENAME(MONTH, [date]) AS MONTH,
               COUNT(DATENAME(MONTH, [date])) AS [Frequency]
FROM (
    SELECT [date], electric_bill_amount, RANK() OVER(ORDER BY electric_bill_amount DESC) as r
    FROM Electric
) tmp
WHERE r <= 10
GROUP BY DATENAME(MONTH, [date])
ORDER BY [Frequency] DESC;