gpt4 book ai didi

sql - t-SQL 查找每个组的前 10 条记录

转载 作者:行者123 更新时间:2023-12-04 10:53:13 24 4
gpt4 key购买 nike

我想弄清楚如何为每组 Trans.TranSID 返回前 10 条记录。

SELECT a.ABID, a.ABName, t.TranSID, SUM(IIF(TranTypeID = 'CO', td.Qty * CAST(td.Price AS money) * - 1, 
td.Qty * CAST(td.Price AS money))) AS TotalSales
FROM Trans t INNER JOIN
TransDetail td ON t.TranID = td.TranID INNER JOIN
ABook a ON t.TranABID = a.ABID
WHERE (t.TranDate BETWEEN CONVERT(DATETIME, '2012-01-01 00:00:00', 102) AND CONVERT(DATETIME, '2013-01-01 00:00:00', 102)) AND
t.TranTypeID in ('SO','CA','CO') AND (t.TranStatus <> 'V')
GROUP BY a.ABID, a.ABName, t.TranSID
HAVING (NOT (a.ABName LIKE '%cash%'))
ORDER BY t.TranSID, TotalSales Desc

我可以将“TOP 10”添加到 select 语句中,但这会为我提供前 10 个帐户,而不考虑组。 Trans.TranSID 有 25 组,我试图只为每个组获得前 10 名。

最佳答案

我认为您正在寻找 ROW_NUMBER()PARTITION BY

SELECT * 
FROM (
SELECT
ROW_NUMBER() OVER(PARTITION BY t.TranSID ORDER BY t.TranSID, SUM(IIF(TranTypeID = 'CO', td.Qty * CAST(td.Price AS money) * - 1, td.Qty * CAST(td.Price AS money))) DESC) as RowNum,
a.ABID,
a.ABName,
t.TranSID,
SUM(IIF(TranTypeID = 'CO', td.Qty * CAST(td.Price AS money) * - 1, td.Qty * CAST(td.Price AS money))) AS TotalSales
FROM Trans t
INNER JOIN TransDetail td
ON t.TranID = td.TranID
INNER JOIN ABook a
ON t.TranABID = a.ABID
WHERE (t.TranDate BETWEEN CONVERT(DATETIME, '2012-01-01 00:00:00', 102) AND CONVERT(DATETIME, '2013-01-01 00:00:00', 102))
AND t.TranTypeID in ('SO','CA','CO')
AND (t.TranStatus <> 'V')
GROUP BY a.ABID, a.ABName, t.TranSID
HAVING (NOT (a.ABName LIKE '%cash%'))
) a
WHERE a.RowNum <=10

这将为分组中的每条记录分配一个行号(由 PARTITION 定义的列,从 1 到 n。从那里,您可以在其上运行 SELECT 以获取每组任意数量的记录。

关于sql - t-SQL 查找每个组的前 10 条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16303343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com