我有一个销售数据的SQL表(如下所示),如何生成一个内联小计的结果集,并按照付费最高的客户的降序对结果进行排序?
因此给出了如下表格:
CUS_ID | PRODUCT | AMOUNT
12 | A | 2.50
12 | B | 5.80
24 | A | 10.00
24 | B | 30.00
我会得到以下结果:
CUS_ID | Product | AMOUNT
24 | A | 10.00
24 | B | 30.00
24 | Total | 30.00
12 | A | 2.50
12 | B | 5.00
12 | Total | 7.50
到目前为止,我可以提出以下问题:
SELECT cus_id, product, amount FROM Sales
UNION ALL
(SELECT cus_id, 'ZZZZ' AS product, SUM(amount) FROM Sales GROUP BY cus_id)
ORDER BY cus_id, product
但是,查询使用'ZZZZ'而不是'Total'(之后可以通过查找和替换来修复),但它不按数量顺序排序。
编辑:请随意发布不涉及排序的答案。其中一些答案实际上对我很有帮助。
答案 0 :(得分:5)
看看像
这样的东西DECLARE @Sales TABLE(
CUS_ID INT,
PRODUCT VARCHAR(20),
AMOUNT FLOAT
)
INSERT INTO @Sales SELECT 12,'A', 2.50
INSERT INTO @Sales SELECT 12,'B', 5.80
INSERT INTO @Sales SELECT 24,'A', 10.00
INSERT INTO @Sales SELECT 24,'B', 30.00
;WITH Vals AS (
SELECT cus_id,
product,
amount,
1 DisplayOrder,
SUM(amount) OVER(PARTITION BY cus_id) OrderTotal
FROM @Sales
UNION ALL
SELECT cus_id,
'Total' AS product,
SUM(amount),
2 DisplayOrder,
SUM(amount)
FROM @Sales
GROUP BY cus_id
)
SELECT cus_id,
product,
amount
FROM Vals
ORDER BY OrderTotal DESC,cus_id,DisplayOrder, product
答案 1 :(得分:4)
因为你很高兴在这里没有排序是我回去工作之前的快速回复。 Sql server中有一个出色的报告功能 - 使用Rollup。它自动为查询添加小计和总行数;基于您正在使用的分组。
使用@ astander的表定义
作为一个非常简单的例子 DECLARE @Sales TABLE(
CUS_ID INT,
PRODUCT VARCHAR(20),
AMOUNT FLOAT
)
INSERT INTO @Sales SELECT 12,'A', 2.50
INSERT INTO @Sales SELECT 12,'B', 5.80
INSERT INTO @Sales SELECT 24,'A', 10.00
INSERT INTO @Sales SELECT 24,'B', 30.00
Select Cus_ID, Product, SUM(Amount)
From @Sales
group by cus_id, product with rollup
返回
Cus_ID Product
----------- -------------------- ----------------------
12 A 2.5
12 B 5.8
12 NULL 8.3
24 A 10
24 B 30
24 NULL 40
NULL NULL 48.3
为了更容易编写报告数据提取并识别小计行,有一个功能 - 分组 - 您可以按组按元素查询。在下面的示例中,它标识了小计和总计行。
DECLARE @Sales TABLE(
CUS_ID INT,
PRODUCT VARCHAR(20),
AMOUNT FLOAT
)
INSERT INTO @Sales SELECT 12,'A', 2.50
INSERT INTO @Sales SELECT 12,'B', 5.80
INSERT INTO @Sales SELECT 24,'A', 10.00
INSERT INTO @Sales SELECT 24,'B', 30.00
select
case
when GROUPING(product) = 1 and GROUPING(cus_id) = 0 then 'Sub Total - Customer -' + cast(Cus_ID as varchar(10))
when GROUPING(product) = 1 and GROUPING(cus_id) = 1 then 'Total'
else cast(Cus_ID as varchar(10)) end as Cus_ID,
PRODUCT,
sum(Amount) as Total_Amount
From @sales
group by cus_id, product with rollup
返回
Cus_ID PRODUCT Total_Amount
-------------------------------- -------------------- ----------------------
12 A 2.5
12 B 5.8
Sub Total - Customer -12 NULL 8.3
24 A 10
24 B 30
Sub Total - Customer -24 NULL 40
Total NULL 48.3
稍微调整就可以让你进行排序。