小计和 SQL
我有一个销售数据的 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”而不是“总计”(可以通过查找和替换来修复)之后),但它不按金额顺序排序。
编辑:请随意发布不涉及排序的答案。有些答案实际上对我很有帮助。
I have a SQL table of sales data (like the one below), how can I generate a result set that inlines the subtotals and idealy sorts the results in descending order of the highest paying customer?
So given a table like the following:
CUS_ID | PRODUCT | AMOUNT
12 | A | 2.50
12 | B | 5.80
24 | A | 10.00
24 | B | 30.00
I would get the following result:
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
So far, I can come with the following query:
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
However, the query uses 'ZZZZ' instead of 'Total' (which can be fixed by find-and-replace afterwards), but it doesn't sort in order of amount.
EDIT: Please feel free to post answers that don't address sorting. Some of the answers were actually pretty helpful to me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看类似的东西
Have a look at something like
因为您很高兴没有在这里进行排序,所以在我回去工作之前,我会快速回复您。 Sql 服务器中有一个很棒的报告功能 - With Rollup。它自动将小计和总计行添加到查询中;基于您正在使用的分组。
作为使用 @astander 的表定义的一个非常简单的示例,
此返回
为了更轻松地编写报告数据提取并识别小计行,有一个函数 - 分组 - 您可以按元素分组进行查询。在下面的示例中,它标识小计和总计行。
返回
稍微调整一下就可以完成您想要的排序。
As you are happy to not have sorting here is a quick response before i get back to work. There is a fantastic reporting feature in Sql server - With Rollup. It adds subtotal and total lines to a query automagically; based on the groupings you are using.
As a very quick example using @astander's table definition
This returns
To make it easier to write your reporting data extract and identify the subtotal rows there is a function - grouping - which you can query by group by elements. In the example below it identifies subtotal and total lines.
Returning
A slight tweak will get it to do the sorting you are after.