I have a table like this.
_id (integer)
event_name(varchar(20))
event_date(timestamp)
Here is some sample data given below.
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
I need the data from above table in below format.
Date count_eventA count_eventB
2013-04-24 2 1
2013-04-25 1 1
hence basically in need the count of each event on each date.
I have tried below query for getting the desired result.
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
Can someone please suggest me to find out a better and optimized query? , or I am following a good approach .
Something on this lines should work:
select event_date::date AS Date ,
count_eventA = sum(case when event_name = 'event_A' then 1 else 0 end),
count_eventB = sum(case when event_name = 'event_B' then 1 else 0 end)
from tblname
GROUP BY (event_date::date))
If you have more events you only need to add more sum(case)
lines :)
The DBEngine only runs through the table once to give you the totals, independiently of the number of the events you want to count: when you have a high rowcount you will observe significant delay with the original query. Should I add this to my answer, you think