按州退还前5名销售额

时间:2013-08-28 10:55:33

标签: sql

我正在尝试编写一个查询,该查询将返回每个提供债务人名称和净总额的州的前5名销售额。我已经提出了以下工作,但是,我确信有更好的方法,特别是如果添加了新的州。

我试图理解WHERE IN语法,但不是我没理解。我很感激你的帮助。

SELECT  TOP 5 data.DebtorNameShort, data.State, data.NetTotal
FROM data
WHERE State= "VI"
ORDER BY NetTotal DESC
UNION ALL
SELECT  TOP 5 data.DebtorNameShort, data.State, data.NetTotal
FROM data
WHERE State= "NS"
ORDER BY NetTotal DESC
UNION ALL
SELECT  TOP 5 data.DebtorNameShort, data.State, data.NetTotal
FROM data
WHERE State= "sa"
ORDER BY NetTotal DESC
UNION ALL
SELECT  TOP 5 data.DebtorNameShort, data.State, data.NetTotal
FROM data
WHERE State= "wa"
ORDER BY NetTotal DESC
UNION ALL
SELECT  TOP 5 data.DebtorNameShort, data.State, data.NetTotal
FROM data
WHERE State= "ta"
ORDER BY NetTotal DESC
UNION ALL
SELECT  TOP 5 data.DebtorNameShort, data.State, data.NetTotal
FROM data
WHERE State= "ac"
ORDER BY NetTotal DESC
UNION ALL
SELECT  TOP 5 data.DebtorNameShort, data.State, data.NetTotal
FROM data
WHERE State= "ql"
ORDER BY NetTotal DESC
UNION ALL SELECT  TOP 5 data.DebtorNameShort, data.State, data.NetTotal
FROM data
WHERE State= "nt"
ORDER BY NetTotal DESC;

2 个答案:

答案 0 :(得分:7)

基于TOP语法,我猜你正在使用SQL Server。您应该能够使用row_number()返回每个州的前5个值:

select DebtorNameShort, State, NetTotal
from
(
  select DebtorNameShort, State, NetTotal,
    row_number() over(partition by state order by NetTotal desc) seq
  from data 
) d
where seq <= 5

row_number()是一个窗口函数,可以为分区中的每个项创建一个顺序值 - 例如,您将按state对数据进行分区。只要您按降序排序NetTotal,就可以过滤最终结果,只返回行数为1-5的行。

答案 1 :(得分:2)

这样的事情应该有用;

WITH cte AS (
   SELECT DebtorNameShort, State, NetTotal,
          ROW_NUMBER() OVER (PARTITION BY State ORDER BY NetTotal DESC) rn
   FROM data
)
SELECT DebtorNameShort, State, NetTotal
FROM cte
WHERE rn <= 5;

这里我使用一个公用表表达式来获取每个状态按NetTotal降序排序的每一行的行号。然后可以在查询中轻松使用该行号来过滤掉每个州的前5行。