SQL Grouping Acct Numbers and Getting Subtotals and Grand Total

梦想的初衷 提交于 2020-01-17 08:11:05

问题


This query...

SELECT ACTNO,SUM(PLAN) AS 'TOTAL PLAN', SUM(FORECAST) AS 'TOTAL FORECAST'
FROM   COST_CENTER
GROUP BY ACTNO

I get the following results:

ACTNO  | TOTAL PLAN | TOTAL FORECAST
100    | 12000      | 20000         
101    | 12000      | 20000         
200    | 1000       | 1500         
201    | 1200       | 2000          
202    |  900       | 1500         
203    |  700       | 1500         
220    | 1500       | 3500         
300    | 1200       | 2000         
301    | 1000       | 3000   

I need to group together certain accounts, get those groups' subtotals, and then add all the subtotals up for a grand total.

The desired result would be something like:

ACTNO  | TOTAL PLAN | TOTAL FORECAST
100    | 12000      | 20000         
101    | 12000      | 20000 
         24000        40000        
200    | 1000       | 1500         
201    | 1200       | 2000          
202    |  900       | 1500         
203    |  700       | 1500 
         3800         6500
220    | 1500       | 3500         
300    | 1200       | 2000         
301    | 1000       | 3000 
         3700         8500
Total   31500        55000

This gets me somewhat close, but not quite in the format I'd like.

SELECT ACTNO, SUM(PLAN), SUM(FORECAST)
FROM     COST_CENTER
WHERE  (ACTNO IN ('100','101'))
GROUP BY ACTNO WITH ROLLUP
...

ACTNO  |            | 
NULL   | 24000      | 40000
100    | 12000      | 20000         
101    | 12000      | 20000 

Thanks for the time and help.


回答1:


You have more control with grouping sets:

SELECT ACTNO, grp, SUM(PLAN), SUM(FORECAST)
FROM (SELECT cc.*,
             (CASE WHEN ACTNO IN ('100', '101') THEN 1
                   WHEN ACTNO IN ('200', '201', '202', '203') THEN 2
                   WHEN ACTNO IN ('220', '300', '301') THEN 3
              END) as grp
      FROM COST_CENTER cc
     ) cc
GROUP BY GROUPING SETS ( (ACTNO, grp), (grp), ());

You can probably remove grp from the SELECT . . . I have never used GROUPING SETS without including the column, though.



来源:https://stackoverflow.com/questions/45449872/sql-grouping-acct-numbers-and-getting-subtotals-and-grand-total

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!