sql查询总和总数

时间:2014-12-11 07:17:30

标签: sql-server aggregate-functions

我必须计算与列system_name对应的每个不同arrival_time(数据库表中的列)的总计数值之和。我的SQL查询是:

SELECT   system_name, COUNT(distinct arrival_time) AS c 
FROM     i2alarmlog 
WHERE    Ack_status = 0 
AND      Direction='CAME' 
AND      system_name in('I2-tciu database',
                        'i2-vcs logging',
                        'Indus1 Vacuum',
                        'Indus2 TCIU',
                        'Indus2 Vacuum',
                        'Septum_SIP2',
                        'TL3 Vacuum') 
GROUP BY system_name 

UNION ALL

SELECT   'sum' system_name,
          Count(distinct arrival_time) 
FROM     i2alarmlog 
WHERE    Ack_status=0 
AND      Direction='CAME'
AND      system_name in( 'I2-tciu database'
                        ,'i2-vcs logging',
                         'Indus1 Vacuum',
                         'Indus2 Vacuum',
                         'Septum_SIP2',
                         'TL3 Vacuum')

当我运行这个sql查询时,sum显示为1841,但实际上是1845。

i2-vcs logging      2
I2-tciu database    2
Indus1 Vacuum       19
Indus2 TCIU         120
Indus2 Vacuum       1691
Septum_SIP2         8
TL3 Vacuum          3
sum                 1841

2 个答案:

答案 0 :(得分:1)

在第二个查询中,distinct部分将应用于所有数据。这意味着,如果您对2种不同的产品具有相同的arrival time,则只会计算一次,而不是每种产品一次。这可以解释您的预期结果和实际结果之间的差异。

你可以做的是:

;with cte as
(SELECT   system_name, COUNT(distinct arrival_time) AS c 
 FROM     i2alarmlog 
 WHERE    Ack_status = 0 
 AND      Direction='CAME' 
 AND      system_name in('I2-tciu database','i2-vcs logging','Indus1 Vacuum','Indus2 TCIU','Indus2 Vacuum','Septum_SIP2','TL3 Vacuum') 
 GROUP BY system_name )

select system_name, c
from cte
union
select 'sum', sum(c) as c
from cte

Demo

答案 1 :(得分:1)

一种解决方案是使用内联视图并计算总和,如下所示:

SELECT   system_name, COUNT(distinct arrival_time) AS c 
FROM     i2alarmlog 
WHERE    Ack_status = 0 
AND      Direction='CAME' 
AND      system_name in('I2-tciu database','i2-vcs logging','Indus1 Vacuum','Indus2 TCIU','Indus2 Vacuum','Septum_SIP2','TL3 Vacuum') 
GROUP BY system_name 

UNION ALL

select 'TotalSum' as TotalSum, sum(s.c) as TotalValue
from
(
    SELECT   system_name, COUNT(distinct arrival_time) AS c 
    FROM     i2alarmlog 
    WHERE    Ack_status = 0 
    AND      Direction='CAME' 
    AND      system_name in('I2-tciu database','i2-vcs logging','Indus1 Vacuum','Indus2 TCIU','Indus2 Vacuum','Septum_SIP2','TL3 Vacuum') 
    GROUP BY system_name 
) s

使用此解决方案达到最大聚合水平(2)(总和(计数(值)))。