使用ROLLUP的Mssql摘要行

时间:2017-08-24 13:03:42

标签: sql sql-server rollup

我尝试使用ROLLUP分组生成摘要行,
这是我的查询

 SELECT nic as NIC,branch_id,SUM(as_share),SUM(as_deposit) as as_deposit,SUM(as_credits) as as_credits,SUM(as_fixed) as as_fixed,SUM(as_ira) as as_ira,SUM(as_saviya) as as_saviya
    FROM As_Member_Account_Details
    GROUP BY nic,branch_id
    WITH ROLLUP

但它给了我这个输出,

112233  1       30.00   0.00    0.00    50.00   0.00    0.00
112233  2       20.00   0.00    0.00    0.00    0.00    0.00
112233  3       0.00    0.00    0.00    0.00    0.00    0.00
112233  NULL    50.00   0.00    0.00    50.00   0.00    0.00
NULL    NULL    50.00   0.00    0.00    50.00   0.00    0.00

最后一行之前的行是不必要的。因为应该只有3个数据行+一个摘要行。如何消除该行

2 个答案:

答案 0 :(得分:0)

WITH CTE_YourQuery AS
(
    SELECT nic as NIC,branch_id,SUM(as_share),SUM(as_deposit) as as_deposit,SUM(as_credits) as as_credits,SUM(as_fixed) as as_fixed,SUM(as_ira) as as_ira,SUM(as_saviya) as as_saviya
    FROM As_Member_Account_Details
    GROUP BY nic,branch_id
    WITH ROLLUP
)
SELECT * 
FROM CTE_YourQuery
WHERE NOT (nic IS NOT NULL AND branch_id IS NULL)

答案 1 :(得分:0)

Grouping sets允许在对数据进行多维数据集时进行更精细的控制。

SELECT nic as NIC
     , branch_id,SUM(as_share)
     , SUM(as_deposit) as as_deposit
     , SUM(as_credits) as as_credits
     , SUM(as_fixed) as as_fixed
     , SUM(as_ira) as as_ira
     , SUM(as_saviya) as as_saviya
FROM As_Member_Account_Details
GROUP BY GROUPING SETS ((nic,branch_id),())