添加SUM函数SQL Server 2012

时间:2015-07-29 20:37:42

标签: sql sql-server tsql

我需要将不同列中的这些分钟​​添加到一起,但是当我尝试运行此语句时,我只看到空白。我已经尝试过多种方法,我认为它在那里有条款。一旦工作,我将再添加4个列!

for (int i = 0; i < 10000000; i++)

2 个答案:

答案 0 :(得分:1)

在记录包含在总和中之前,每个记录的WHERE子句的所有条件必须同时为TRUE。

由于您看到一个空白输出,看起来您没有任何记录,其中serv1,serv2,serv3和serv4同时都是NOT NULL。

由于看起来你想要对每个mins-columns求和,只有当相应的serv-column包含“Speech Language Therapy”时,考虑将此条件移动到查询的SELECT部分,如下所示:

WITH CTE AS (
    SELECT [School Name],
       SUM(CASE WHEN serv1 = 'Speech Language Therapy' THEN mins1 ELSE 0 END) as mins1
      ,SUM(CASE WHEN serv2 = 'Speech Language Therapy' THEN mins2 ELSE 0 END) as mins2
      ,SUM(CASE WHEN serv3 = 'Speech Language Therapy' THEN mins3 ELSE 0 END) as mins3
      ,SUM(CASE WHEN serv4 = 'Speech Language Therapy' THEN mins4 ELSE 0 END) as mins4
    FROM [dbo].[George].[TEST_TEMP_TABLE]
    GROUP BY [School Name]
)
SELECT [School Name]
    , mins1, mins2, mins3, mins4
    , mins1 + mins2 + mins3 + mins4 as Minutes
FROM cte
ORDER BY [School Name]

在这里,我已将mins1..mins4的计算移动到CTE中,以便更容易计算CTE外所有4的总和(以避免再次重复每个CASE语句)。

另请注意,当您已经拥有serv1 IS NOT NULL条件时,无需检查serv1 = 'Speech Language Therapy'

答案 1 :(得分:0)

您可以重新编写SQL,就像这样:

SELECT [School Name],
   SUM(coalesce(mins1,0)) as mins1total,
   SUM(coalesce(mins2,0)) as mins2total,
   SUM(coalesce(mins3,0)) as mins3total,
   SUM(coalesce(mins4,0)) as mins4total,
   SUM(coalesce(min1,0) + coalesce(min2,0) + coalesce(min3,0) + coalesce(min4,0)) as alltotal
 FROM [dbo].[George].[TEST_TEMP_TABLE]
 WHERE 
   serv1 = 'Speech Language Therapy'
   AND serv2 = 'Speech Language Therapy'
   AND serv3 = 'Speech Language Therapy'
   AND serv4 = 'Speech Language Therapy'
GROUP BY [School Name]
ORDER BY [School Name]