我有一张表格,其中有客户制作的付款详细信息。列如下:
ID, ClientID, Amount
现在我想通过客户 ID 找到 5 个最大金额组。
我找到DENSE_RANK()
了,但它不适合我,因为我想找到sum of amount。
谢谢。
我有一张表格,其中有客户制作的付款详细信息。列如下:
ID, ClientID, Amount
现在我想通过客户 ID 找到 5 个最大金额组。
我找到DENSE_RANK()
了,但它不适合我,因为我想找到sum of amount。
谢谢。
请试试:
SELECT
ClientID,
SUM(Amount) Amount
FROM(
SELECT ROW_NUMBER() OVER (PARTITION BY ClientID ORDER BY Amount DESC) DR,
ClientID,
Amount
FROM YourTable
)x WHERE x.DR<=5
GROUP BY ClientID
ORDER BY ClientID
;WITH totalSum
AS
(
SELECT ClientID, SUM(Amount) totalAmount
FROM tableName
GROUP BY ClientID
)
SELECT ClientID, totalAmount
FROM
(
SELECT ClientID, totalAmount,
DENSE_RANK() OVER (ORDER BY totalAmount DESC) rn
FROM totalSum
) s
WHERE rn <= 5
SELECT
ID,
ClientID,
Amount
FROM
PaymentDetails
GROUP BY
ID
HAVING
Amount = SUM(Amount)
这对你有用吗?(不确定我是否理解您的问题)如果您想要 TOP 5 的总数,就是这样。SUM()
查找每个客户的TOP 5
金额的查询是不同的。
;WITH OrderingCTE AS
(
SELECT ID
,ClientID
,Amount = SUM(Amount)
,rNum = ROW_NUMBER() OVER (PARTITION BY ClientID ORDER BY SUM(Amount) DESC)
FROM MyTable
GROUP BY ID
,ClientID
)
SELECT *
FROM OrderingCTE
WHERE rNum <=5