如何优化以下查询?

时间:2013-06-06 09:37:59

标签: sql postgresql postgresql-performance sql-tuning

我有一张这样的桌子。

_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 

有人可以建议我找一个更好的优化查询吗? ,或者我正在采取一种好的方法。

3 个答案:

答案 0 :(得分:3)

这方面的东西应该有效:

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))

如果您有更多活动,则只需添加更多sum(case)行:)

DBEngine只运行一次表来为您提供总数,与您想要计算的事件数量无关:当您有一个高行数时,您将观察到原始查询的显着延迟。我应该将此添加到我的答案中,您认为

答案 1 :(得分:1)

比案例语法更简单(更清晰):

select
    event_date::date as Date,
    count(event_name = 'event_A' or null) count_eventA,
    count(event_name = 'event_B' or null) count_eventB
from t
group by 1

答案 2 :(得分:0)