我有一张这样的桌子。
_id (integer)
event_name(varchar(20))
event_date(timestamp)
下面是一些示例数据。
ID event_date event_name
101 2013-04-24 18:33:37.694818 event_A
102 2013-04-24 20:34:37.000000 event_B
103 2013-04-24 20:40:37.000000 event_A
104 2013-04-25 01:00:00.694818 event_B
105 2013-04-25 12:00:15.694818 event_A
我需要上表中以下格式的数据。
Date count_eventA count_eventB
2013-04-24 2 1
2013-04-25 1 1
因此基本上需要每个日期的每个事件的计数。
我已尝试以下查询以获得所需的结果。
SELECT A.date1 AS Date ,
A.count1 AS count_eventA,
B.count2 AS count_eventB,
FROM
(SELECT count(event_name)AS count1,
event_date::date AS date1
FROM tblname
WHERE event_name='event_A'
GROUP BY (event_date::date))AS A
LEFT JOIN
(SELECT count(event_name)AS count1,
event_date::date AS date1
FROM tblname
WHERE event_name='event_B'
GROUP BY (event_date::date))AS B ON A.date1=B.date2
有人可以建议我找出更好和优化的查询吗?,或者我正在遵循一个好的方法。