我有一个包含以下列和示例数据的表。
(此数据是查询的输出,因此我必须在FROM()语句中使用该查询)
Type| Time | Count
--------------------------------
1 |2013-05-09 12:00:00 | 71
2 |2013-05-09 12:00:00 | 48
3 |2013-05-09 12:00:00 | 10
3 |2013-05-09 13:00:00 | 4
2 |2013-05-16 13:00:00 | 30
1 |2013-05-16 13:00:00 | 31
1 |2013-05-16 14:00:00 | 4
3 |2013-05-16 14:00:00 | 5
我需要根据时间对数据进行分组,以便我的输出看起来像这样
AlarmType1 | AlarmType2 |AlarmType3| AlarmTime
--------------------------------
71 | 48 | 10 | 2013-05-09 12:00:00
31 | 30 | 4 | 2013-05-09 13:00:00
4 | 0 | 5 | 2013-05-09 14:00:00
我试过这个查询
SELECT
SUM(IF (AlarmType = '1',1,0)) as AlarmType1,
SUM(IF (AlarmType = '2',1,0)) as AlarmType2,
SUM(IF (AlarmType = '3',1,0)) as AlarmType3,
AlarmHour
FROM 'Table1'
GROUP BY Time
但这不起作用,因为我在我的查询中缺少Count,必须调整我的查询计数
答案 0 :(得分:1)
你需要SUM(Count),而不是SUM(1):
SELECT
SUM(IF (AlarmType = '1',Count,0)) as AlarmType1,
SUM(IF (AlarmType = '2',Count,0)) as AlarmType2,
SUM(IF (AlarmType = '3',Count,0)) as AlarmType3,
AlarmHour
FROM 'Table1'
GROUP BY Time
答案 1 :(得分:0)
您的table1
是您的子查询吗?好吧,它必须有它的别名所以它将是那样的
SELECT
SUM(IF (AlarmType = '1',1,0)) as AlarmType1,
SUM(IF (AlarmType = '2',1,0)) as AlarmType2,
SUM(IF (AlarmType = '3',1,0)) as AlarmType3,
AlarmHour
FROM (subquery giving table1) as subTable
GROUP BY subtable.Time
修改强>
至于求和,为什么不使用多个group by
?例如。 GROUP BY Type, Time
并显示每个组的类型并输入SELECT Type,Time,Sum(Count) ...
?
好的,我现在明白了你想要实现的目标。如果您想“添加列”,则必须使用JOINS
。因此,为您需要的每个列(每个AlarmType计数)创建单个查询,并将它们连接到commond值whitch is alarm of alarm。
答案 2 :(得分:0)
SELECT SUM(IF (AlarmType = '1',1,0)) as AlarmType1,
SUM(IF (AlarmType = '2',1,0)) as AlarmType2,
SUM(IF (AlarmType = '3',1,0)) as AlarmType3,
AlarmHour
FROM (your query) as t group by t.Time