0

我对 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

对于 id 为 7 的应用程序,我的请求在 2 周内计算我的事件表(日志表)上每天的“ACTION*”数量。但问题是它没有显示没有记录任何操作的一天。

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

感谢您的帮助

4

2 回答 2

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
于 2013-02-12T17:04:48.843 回答
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 表中的所有日期,并询问第二个参数的计数。

于 2013-02-12T17:54:10.660 回答