Question

I'm using SQL Server 2008 R2 and have a table as:

table origin

And I need to get it summarized as:

table result

I'm trying using cube/rollup and grouping functions, but I'm stuck on how to resolve it. So I would ask if someone could, please, help and show me the query for this result.

Thanks in advance.

Was it helpful?

Solution

As I said, I was stuck on how to resolve it. But I've got some great links which helped me a lot to think and resolve it, for example: http://blogs.msdn.com/b/craigfr/archive/2007/09/21/aggregation-with-rollup.aspx

This is the way I resolved:

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top