3

我正在尝试对同一个表中的两列进行求和,但求和的条件不同。我遇到的问题是试图将结果放入两个不同的列。如果我使用这个查询,我会得到笛卡尔积。

SELECT SUM(p1.arc_baseEventCount)  AS 'Total Logger Event Count',
       SUM(p2.arc_deviceCustomNumber3) AS 'Total Connector Event Count'
FROM EVENTS AS p1, EVENTS AS p2
WHERE p2.arc_name = "Connector Raw Event Statistics"

当我运行这个查询时,我得到了预期的结果,但结果是两行而不是两列。

SELECT SUM(arc_baseEventCount) 'total event count'
FROM Events
UNION ALL
SELECT SUM(arc_deviceCustomNumber3)
FROM EVENTS
WHERE arc_name = "Connector Raw Event Statistics"

我知道我很接近,但我肯定错过了一些东西。

4

2 回答 2

2

你可以用CASE这个,

SELECT  SUM(arc_baseEventCount) 'total event count', 
        SUM(CASE WHEN arc_name = 'Connector Raw Event Statistics' THEN arc_baseEventCount ELSE NULL END) 'Connector Raw Event Statistics'
FROM    Events

更新 1

SELECT  SUM(arc_baseEventCount) 'total event count', 
        SUM(CASE WHEN arc_name = 'Connector Raw Event Statistics' THEN arc_baseEventCount ELSE NULL END) 'total_1',
        SUM(CASE WHEN name = 'Connector Raw Event Statistics' THEN arc_deviceCustomNumber3 ELSE NULL END) 'total_2'
FROM    Events
于 2013-02-14T02:21:53.353 回答
0

您可以使用子查询

select distinct sum(p1.arc_baseEventCount)  AS 'Total Logger Event Count'
, (select sum(p2.arc_deviceCustomNumber3) 
from events p2 on p1.something = p2.something
where p2.arc_name = 'Connector Raw Event Statistics') as 'Total Connector Event Count'

from events p1 
于 2013-02-14T02:36:20.493 回答