0

我有一个包含以下列和示例数据的表。

(此数据是查询的输出,因此我必须在 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

但这不起作用,因为我在我的查询中缺少计数,必须在我的查询中调整计数

4

3 回答 3

2

您需要 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
于 2013-10-22T07:15:16.543 回答
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 计数)创建单个查询,并将它们加入到共同值上,即警报时间。

于 2013-10-22T06:42:29.097 回答
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
于 2013-10-22T06:46:57.857 回答