我有一个customer表如下:
customername, ordername, amount
=============================
bob, book, 20
bob, computer, 40
steve,hat, 15
bill, book, 12
bill, computer, 3
steve, pencil, 10
bill, pen, 2
我想运行查询以获得以下结果:
customername, ordername, amount
=============================
bob, computer, 40
bob, book, 20
bob, ~total~, 60
steve, hat, 15
steve, pencil, 10
steve, ~total~,25
bill, book, 12
bill, computer, 3
bill, pen, 2
bill, ~total~, 17
我希望每个客户的金额从最大订购到最小,新订单名称为“~total~”(必须始终是每个客户的最后一行),结果为同一客户的所有金额的总和。 所以,在上面的例子中,bob应该是第一个,因为总数= 60,steve第二个(总数= 25)并且计算第三个(总数= 17)。
答案 0 :(得分:8)
使用:
SELECT x.customername,
x.ordername,
x.amount
FROM (SELECT a.customername,
a.ordername,
a.amount,
y.rk,
1 AS sort
FROM CUSTOMERS a
JOIN (SELECT c.customername,
ROW_NUMBER() OVER (ORDER BY SUM(c.amount) DESC) AS rk
FROM CUSTOMERS c
GROUP BY c.customername) y ON y.customername = a.customername
UNION ALL
SELECT b.customername,
'~total~',
SUM(b.amount),
ROW_NUMBER() OVER (ORDER BY SUM(b.amount) DESC) AS rk,
2 AS sort
FROM CUSTOMERS b
GROUP BY b.customername) x
ORDER BY x.rk, x.customername, x.sort, x.amount DESC
您可以查看使用GROUP BY ROLLUP
,但ordername
值为NULL,因此您必须对其进行后处理才能将其替换为“~total〜”...