3

我正在尝试编写一个查询,该查询将返回每个州提供债务人姓名和净总额的前 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;
4

2 回答 2

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 的行。

于 2013-08-28T10:59:42.160 回答
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 行。

于 2013-08-28T11:00:18.133 回答