在按日期分组的SQL查询中包括零

时间:2018-11-19 05:54:34

标签: sql postgresql

我有一张表格,列出了人们的问题(又名任务),我想算出有多少被标记为“准时关闭”。

说实话,我对SQL查询的经验还不是很丰富,我正试图仅按月提取所有已关闭任务的数据。

以下是(postgres)SQL查询:

SELECT
    cast(date_trunc('month', b.closed_on) as date) AS time,
    count(distinct a.issue_id) as "Tasks Closed On Time"
from redmine_issues_summary a
left join redmine_issues_summary b on cast(date_trunc('month', b.closed_on) as date) = cast(date_trunc('month', a.closed_on) as date)
WHERE
  a.assignee_groups in('Modelling','Global') and
  a.tracker in('Administration','Costing','N.A.','Prototype Shop','Simulation') and 
  a.closed_on_time = 'On Time'
group by cast(date_trunc('month', b.closed_on) as date)
ORDER BY cast(date_trunc('month', b.closed_on) as date) 

但是,我在联接上做错了,因为我没有得到计数为零的行。

有人可以帮我吗?

编辑:

@Tim的回答帮助我找到了解决方案。

SELECT
    cast(date_trunc('month', b.closed_on) as date) AS time,
    SUM(case when a.closed_on_time = 'On Time' and a.assignee_groups in('LOH_Modelling&Analysis','LOH_Modelling&Analysis, Global_CAE','LOH_Modelling&Analysis, KOP_CAE, Global_CAE','Project_Admin, LOH_Modelling&Analysis','Project_Admin, LOH_Modelling&Analysis, Global_CAE') and
  a.top_parent_project_name in('1_Global GKN Projects') and 
  a.tracker in('Administration') THEN 1 ELSE 0 END) as "Tasks Closed On Time"
from redmine_issues_summary a
left join redmine_issues_summary b on cast(date_trunc('month', b.closed_on) as date) = cast(date_trunc('month', a.closed_on) as date)
group by cast(date_trunc('month', b.closed_on) as date)
ORDER BY cast(date_trunc('month', b.closed_on) as date)

2 个答案:

答案 0 :(得分:0)

尝试使用条件聚合:

SELECT
    cast(date_trunc('month', b.closed_on) as date) AS time,
    sum(case when a.closed_on_time = 'On Time' THEN 1 ELSE 0 END) as "Tasks Closed On Time"
from redmine_issues_summary a
left join redmine_issues_summary b
    on cast(date_trunc('month', b.closed_on) as date) = cast(date_trunc('month', a.closed_on) as date)
WHERE
    a.assignee_groups in('Modelling','Global') and
    a.tracker in('Administration','Costing','N.A.','Prototype Shop','Simulation')
group by
    cast(date_trunc('month', b.closed_on) as date)
ORDER BY
    cast(date_trunc('month', b.closed_on) as date) 

这假定您不想包括不在指定的受让人或跟踪者组中的任何记录。如果您要做要包括这些记录,那么我的答案将需要更新。

答案 1 :(得分:0)

在选择中使用左表, 您在选择中使用了右表列(b.closed_on),则需要更改(a.closed_on

SELECT
    cast(date_trunc('month', a.closed_on) as date) AS time,
    count(distinct a.issue_id) as "Tasks Closed On Time"
from redmine_issues_summary a
left join redmine_issues_summary b on cast(date_trunc('month', b.closed_on) as date) = cast(date_trunc('month', a.closed_on) as date)
WHERE
  a.assignee_groups in('Modelling','Global') and
  a.tracker in('Administration','Costing','N.A.','Prototype Shop','Simulation') and 
  a.closed_on_time = 'On Time'
group by cast(date_trunc('month', a.closed_on) as date)
ORDER BY cast(date_trunc('month', a.closed_on) as date)