按列分组

时间:2017-06-23 13:52:54

标签: sql sql-server sql-server-2012

我在查询结果的底部有一个我需要Total的列(PL.UNITS),是否可以对已经求和的PL.UNITS求和?

请参阅下面的查询。

SELECT ID.DUEDATE AS [DUE DATE], CD.RENEWALDATE, CD.RENEWALSTATUS, CD.CONTRACTNUMBER, L.LOCNAME, L.LOCADDRESS1, L.LOCADDRESS2, L.LOCADDRESS3, L.LOCADDRESS4, L.POSTCODE, SUM(PL.UNITS) AS UNITS from CLIENTDETAILS CD 

INNER JOIN LOCATIONS L ON CD.CLIENTNUMBER = L.CLIENTNUMBER 
INNER JOIN ITEMDETAILS ID ON L.LOCNUMBER = ID.LOCNUMBER
INNER JOIN PLANT PL ON ID.CODE = PL.CODE

WHERE L.OWNER = 210 and L.STATUSLIVE = 1 and ID.DUEDATE > '01/01/2017' 

GROUP BY ID.DUEDATE, CD.RENEWALDATE, CD.RENEWALSTATUS, CD.CONTRACTNUMBER, L.LOCNAME, L.LOCADDRESS1, L.LOCADDRESS2, L.LOCADDRESS3, L.LOCADDRESS4, L.POSTCODE

1 个答案:

答案 0 :(得分:2)

最好在前端开发中做这类事情。不过,这里有一个例子(快速和脏,但显示了sql-server的想法):

SELECT  COALESCE(a.id, 'total') AS id
,       SUM(a.thing) AS thing_summed
FROM    (
            SELECT '1' id
            ,   1 thing
            UNION
            SELECT '2'
            ,   2 thing
            UNION
            SELECT '1'
            ,   3 thing
        ) AS a
GROUP BY ROLLUP(a.id) 

结果:

+-------+--------------+
|  id   | thing_summed |
+-------+--------------+
| 1     |            4 |
| 2     |            2 |
| total |            6 |
+-------+--------------+