笛卡尔积 - 同一表中的SUM两列

时间:2013-02-14 02:18:50

标签: mysql sql

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

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"

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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