我正在使用SQL Server 2008 R2,并且有一个表格:
我需要将其归纳为:
我正在尝试使用立方体/汇总和分组功能,但我仍然坚持如何解决它。 所以我会问,是否有人可以帮助并向我显示此结果的查询。
提前致谢。
答案 0 :(得分:0)
正如我所说, 坚持如何解决它。但是我有一些很棒的链接帮助我思考和解决它,例如:http://blogs.msdn.com/b/craigfr/archive/2007/09/21/aggregation-with-rollup.aspx
这是我解决的方式:
select
0 order_customer,
customer_ID,
0 order_product,
product_ID,
0 tipo_linha,
subProduct_description,
subProduct_balance
from products
union all
select
GROUPING(customer_ID) order_customer,
customer_ID,
GROUPING(product_ID) order_product,
product_ID,
1 tipo_linha,
CASE
WHEN (GROUPING(customer_ID) = 1) THEN 'Grand Total'
WHEN (GROUPING(product_ID) = 1) THEN 'Total of products by customer '
+ cast(customer_ID as varchar)
ELSE 'Total by product ' + cast(product_ID as varchar)
END msg,
sum(subProduct_balance ) balance
from products
group by rollup(customer_ID, product_ID)
order by order_customer, customer_ID, order_product, product_ID, tipo_linha