将SQL查询限制为天

时间:2016-05-27 12:22:13

标签: sql postgresql

我使用此SQL查询按天制作状态报告:

CREATE TABLE TICKET(
 ID INTEGER NOT NULL,
 TITLE TEXT,
 STATUS INTEGER,
 LAST_UPDATED DATE,
 CREATED DATE
)
;

查询:

SELECT t.created,
       COUNT(CASE WHEN t.status = '1' THEN 1 END) as cnt_status1,
       COUNT(CASE WHEN t.status = '2' THEN 1 END) as cnt_status2,
       COUNT(CASE WHEN t.status = '3' THEN 1 END) as cnt_status3,
       COUNT(CASE WHEN t.status = '4' THEN 1 END) as cnt_status4
FROM ticket t
GROUP BY t.created

如何将此查询限制为过去7天? 此外,我想将结果分开。例如,我想将第一个日期分为24小时,第二个日期为24小时等等。

预期结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助:

SELECT   TO_CHAR(t.created, 'YYYY-MM-DD') AS created_date,
         COUNT(CASE WHEN t.status = '1' THEN 1 END) as cnt_status1,
         COUNT(CASE WHEN t.status = '2' THEN 1 END) as cnt_status2,
         COUNT(CASE WHEN t.status = '3' THEN 1 END) as cnt_status3,
         COUNT(CASE WHEN t.status = '4' THEN 1 END) as cnt_status4
FROM     ticket t
WHERE    t.created >= SYSDATE-7
GROUP BY TO_CHAR(t.created, 'YYYY-MM-DD')
ORDER BY created_date;

我使用oracle函数进行日期转换。我相信你会找到相应的postgresql。