MSSQL:得到总计的小计

时间:2017-06-15 18:02:01

标签: sql sql-server tsql sql-server-2012 sql-server-2008-r2

如何编写查询以获取总计的小计?示例如下。

select
task_id,
client_id,
SUM(value1 + value2) AS 'Total 1',
SUM(value3 + value4) AS 'Total 2',
--pseudocode
SUM(Total 1 + Total 2) AS 'Total 1 + Total 2'
from table1
GROUP BY task_id,client_id

预期结果:

task_id | client_id | Total 1 | Total 2 | Total 1 + Total 2 |
   1         4          2          4            6

2 个答案:

答案 0 :(得分:1)

它可以将它包装在子查询中:

SELECT 
    task_id
    , client_id
    , [Total 1]
    , [Total 2]
    , SUM([Total 1], [Total 2]) AS 'Total 1 + Total 2'
FROM
(
  select
    task_id,
    client_id,
    SUM(value1 + value2) AS 'Total 1',
    SUM(value3 + value4) AS 'Total 2',
    --pseudocode
    SUM(Total 1 + Total 2) AS 'Total 1 + Total 2'
  from table1
  GROUP BY task_id,client_id
) a 
GROUP BY task_id, client_id

或者,您可以简单地添加原始值:

,而不是使用SUM
select
task_id,
client_id,
SUM(value1 + value2) AS 'Total 1',
SUM(value3 + value4) AS 'Total 2',
--pseudocode
value1 + value2 + value3 + value4 AS 'Total 1 + Total 2'
from table1
GROUP BY task_id,client_id

答案 1 :(得分:1)

您不能在同一个选择中重复使用列别名。相反,只需重复操作:

select task_id, client_id,
       SUM(value1 + value2) AS [Total 1],
       SUM(value3 + value4) AS [Total 2],
       SUM(value1 + value2 + value3 + value4) AS [Total 1 + Total 2]
from table1
group by task_id, client_id;

如果重复操作很麻烦,那么可以考虑子查询或CTE。