开发者

SQL Server conditional rollup (only rollup when there are multiple subgroup)

开发者 https://www.devze.com 2023-03-20 22:37 出处:网络
I have the following SQL. Most of the G1 and G2 are one-to-one relationship. A few are one-to-many relationship. The following SQL will show too many 开发者_StackOverflow社区\"Total2\". Is it possible

I have the following SQL. Most of the G1 and G2 are one-to-one relationship. A few are one-to-many relationship. The following SQL will show too many 开发者_StackOverflow社区"Total2". Is it possible to remove these Total2 rows when G1 and G2 are one-to-one?

SELECT  CASE WHEN GROUPING_ID(G1) = 1 THEN 'Total1' ELSE G1 END,
        CASE WHEN GROUPING_ID(G2) = 1 THEN 'Total2' ELSE G2 END,
        SUM(a),
        SUM(b),
        count(*)
FROM    data
GROUP BY
        G1, G2 WITH ROLLUP


unfortunately I dont have any idea how to avoid subquery here

With subquery we may use one trick - when we group by G1 and at the same time G1 and G2 have 1-to-1 relationship (i.e. equal) it means that max(G2) will equal to min(g2) and this condition will allow us to build a where clause and get rid of them

Code may be like this

select * from
(
SELECT  CASE 
WHEN GROUPING_ID(G1) = 1 THEN 'Total1' ELSE G1 END as G1,    
MIN(g2) as min_g2, 
max(g2) as max_g2,
CASE WHEN GROUPING_ID(G2) = 1 THEN 'Total2' ELSE G2 END as G2,  
       SUM(a) as SUM_A,       
         SUM(b) as SUM_B,       
           count(*) as cnt
FROM    data 
GROUP BY         G1, G2 
WITH ROLLUP 
) t
where 
not (min_g2 = max_g2 and g2 = 'Total2')
0

精彩评论

暂无评论...
验证码 换一张
取 消