2

我有一个包含三个相关字段的表“任务”:date_created、date_updated 和 is_close。

我有一个简单的查询来计算创建的任务数:

SELECT task.date_created, count(task.is_closed)
FROM task
GROUP BY task.date_created
ORDER BY task.date_created

我想要的是每天关闭的任务数量。出于我们的目的,任务的最终更新日期是 is_closed='true'

所以,决赛桌应该看起来像

date      opened  closed
04/01/13  8       6
04/02/13  9       5
4

2 回答 2

0

您可以使用以下CASE语句COUNT

SELECT task.date_created, 
    count(1) opened, 
    count(case when is_closed = 'true' then 1 end) closed
FROM task
GROUP BY task.date_created
ORDER BY task.date_created

SQL 小提琴演示

鉴于您的意见,这里是使用一对夫妇的方法Common Table Expressions

WITH OPENED AS (
    SELECT date_created, count(1) opened
    FROM task
    GROUP BY date_created
  ) ,
CLOSED AS (
    SELECT date_updated, count(1) closed
    FROM task
    WHERE is_closed = 'true'
    GROUP BY date_updated
  )
SELECT D.YourDateField, o.opened, c.closed
FROM YourDateTable D
    LEFT JOIN Opened O ON D.YourDateField = O.Date_Created
    LEFT JOIN CLosed C ON D.YourDateField = C.Date_Created

正如 Gordon 指出的那样,aFULL OUTER JOIN也可以。我只是更喜欢使用日期表来播种。创建表一次,然后在需要的任何地方使用它。

于 2013-04-29T18:37:39.163 回答
0

我认为您需要将其作为两个子查询来执行。这是一种方法,使用full outer join

select coalesce(a.date_created, c.date_updated) as thedate,
       coalesce(a.opened, 0) as opened,
       coalesce(c.closed, 0) as closed
from (select date_created, count(*) as opened
      from task
      group by date_created
     ) a full outer join
     (select date_updated, count(*) as closed
      from task
      where is_closed = 1  -- or whatever the value is
      group by date_updated
     ) c
     on a.date_created = c.date_updated

保证所有日期都存在,full outer join即使您只有关闭或打开。

于 2013-04-29T18:44:08.470 回答