按要求在我的组中包含计数0

时间:2013-02-12 17:00:21

标签: sql postgresql count group-by

我有一个对postgresql的COUNT + GROUP BY请求。

SELECT date_trunc('day', created_at) AS "Day" , 
       count(*) AS "No. of actions" 
FROM events 
WHERE created_at > now() - interval '2 weeks' 
  AND "events"."application_id" = 7 
  AND ("what" LIKE 'ACTION%') 
GROUP BY 1 
ORDER BY 1

我的请求在我的事件表(日志表)中计算每天“ACTION *”的数量,在2周内我的应用程序的ID为7.但问题是它没有显示何时有一天没有任何记录的行动。

我知道这是因为我的WHERE子句,所以我尝试了一些关于JOIN请求的东西,但没有给我很好的答案。

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

制作日期表:

CREATE TABLE "myDates" (
    "DateValue" date NOT NULL
);

INSERT INTO "myDates" ("DateValue") 
select to_date('20000101', 'YYYYMMDD') + s.a as dates from generate_series(0,36524,1) as s(a);

然后离开加入:

SELECT  d.DateValue AS "Day" , 
        count(*) AS "No. of actions"    
FROM    myDates d left join events e on date_trunc('day', "events"."created_at") = d.DateValue
WHERE   created_at > now() - interval '2 weeks' AND 
        "events"."application_id" = 7 AND 
        ("what" LIKE 'ACTION%') 
GROUP BY 1 ORDER BY 1

答案 1 :(得分:0)

好的朋友帮了我,答案是:

SELECT  "myDates"."DateValue" AS "Day" , 
    (select count(*) from events WHERE   date_trunc('day', "events"."created_at") = "myDates"."DateValue" AND 
    ("events"."application_id" = 4) AND 
    ("events"."what" LIKE 'ACTION%'))  AS "No. of actions"    
FROM    "myDates" 
where ("myDates"."DateValue" > now() - interval '2 weeks') AND ("myDates"."DateValue" < now())

因此我们需要询问MyDates表中的所有日期,并询问第二个参数的计数。