0

我正在使用 SQL Server 2008 R2 并有一个表:

表原点

我需要把它总结为:

表格结果

我正在尝试使用多维数据集/汇总和分组功能,但我坚持如何解决它。所以我会问是否有人可以,请帮助并向我展示这个结果的查询。

提前致谢。

4

1 回答 1

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 
于 2013-06-25T16:45:58.770 回答