我在解决如何解决方面遇到了一些问题,但我根本无法得到答案。这是我的问题。
我有一个mySQL表,如下所示:
cust_id,date_removed,station_removed,date_arrived,station_arrived
6,"2010-02-02 13:57:00",56,"2010-02-02 13:58:00",77
6,"2010-02-02 15:12:00",66,"2010-02-02 15:12:00",56
30,"2010-02-05 11:36:00",32,"2010-02-05 11:37:00",14
30,"2010-02-05 11:37:00",14,"2010-02-05 11:37:00",20
30,"2010-02-05 12:41:00",85,"2010-02-05 12:43:00",85
30,"2010-02-05 12:44:00",85,"2010-02-05 12:46:00",85
30,"2010-02-06 13:15:00",8,"2010-02-06 13:17:00",20
30,"2010-02-06 13:18:00",23,"2010-02-06 13:19:00",23
30,"2010-02-06 13:20:00",32,"2010-02-06 13:21:00",39
30,"2010-02-06 13:21:00",11,"2010-02-06 13:21:00",23
30,"2010-02-06 13:21:00",76,"2010-02-06 13:22:00",32
每个字段中相应的数据类型如下: cust_id:varchar() date_removed:datetime station_removed:int date_arrived:datetime station_arrived:int
接下来,我被要求进行查询以获取当天使用的每个电台的计数,以获得如下表:
station 2010-02-02 2010-02-05 2010-02-06
56 2 0 0
66 1 0 0
32 0 1 2
14 0 2 0
85 0 2 0
8 0 0 1
23 0 0 2
11 0 0 1
76 0 0 1
77 1 0 0
20 0 1 1
39 0 0 1
其中列是天,行是每个站。我也不是一个非常好的mySQL用户。
有人可以帮我解决这个问题吗?
提前谢谢
答案 0 :(得分:0)
使用此查询:
select stations.name as station,
(select count(*) from table where date(date_arrived)='2010-02-02' and (station_removed=stations.name or station_arrived=stations.name)) as '2010-02-02'
(select count(*) from table where date(date_arrived)='2010-02-05' and (station_removed=stations.name or station_arrived=stations.name)) as '2010-02-05'
(select count(*) from table where date(date_arrived)='2010-02-06' and (station_removed=stations.name or station_arrived=stations.name)) as '2010-02-06'
from
(select station_removed as name from table
union
select station_arrived from table ) stations ;