在Oracle-SQL中将两个日期分组为一个

时间:2013-04-29 18:35:53

标签: sql oracle date count group-by

我有一个包含三个相关字段的表'task':date_created,date_updated和is_closed。

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

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

2 个答案:

答案 0 :(得分: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 Fiddle Demo

鉴于您的意见,这是一种方法,使用一对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

戈登指出,FULL OUTER JOIN也可以。我只是喜欢使用日期表来播种。创建一次表,并在任何需要的地方使用它。

答案 1 :(得分: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保证所有日期都存在,即使您只关闭或打开。