SQL查询:按日期多个计数组

时间:2015-05-28 17:42:47

标签: mysql group-by

我的mySQL数据库中有2个表:

while True:

   print "Please choose from one of the five following options:"

   print " 1. 10^1\n 2. 10^2\n 3. 10^3\n 4. 10^4\n 5. 10^5\n"
choice = raw_input()

if choice == 1:
    print "1"
elif choice == 2:
    print "2"
elif choice == 3:
    print "3"
elif choice == 4:
    print "4"
elif choice == 5:
    print "5"

else:
    print "Not a valid choice!\n"

我需要一个返回类似内容的查询:

Table Sensor
_id    Name
1      Sensor1
2      Sensor2

Table History
_id    Sensor_fk    Date 
1      1            2015-05-24
2      2            2015-05-27
3      1            2015-05-28
4      1            2015-05-28
5      2            2015-05-28
...

这是按日期分组的2个传感器的数量。我将用这些数据填充条形图。 有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:0)

您需要为每个Sensor的两个单独的GROUP BY子句执行UNION。像

(Select count(*) as Sensor1 from History h
     where h.Sensor_FK = 1
     group by DateField
)

Union

(Select Count(*) as Sensor2 from History h
    whre h.Sensor_FK = 2
    group by DateField
   )

答案 1 :(得分:0)

我明白了。

SELECT h.date as Date, 
count(CASE WHEN h.sensor_fk = 1 THEN h.sensor_fk END) as 'Sensor1',
count(CASE WHEN h.sensor_fk = 2 THEN h.sensor_fk END) as 'Sensor2'
FROM history h
GROUP BY Date