Oracle SQL帮助计算两种不同的方式,但具有共同的分组

时间:2012-09-13 13:30:31

标签: sql oracle

我有一个表格,其中为每个条目包含incident_idstatus(让我们说opencloseddate_raised(日期)和{ {1}}(日期)。

我想显示一个表,该表计算关闭日期关闭的事件数(因此closure_date计数incident_id),以及保持打开的事件数(计数{ {1}}同一天的status='closed' and closure_date is not null

如果我对你感到困惑,那么表格就像这样:

incident_id

我已经管理了一个表,它会像这样关闭事件的数量:

status='open'

我已经尝试了几个小时来让其他计数工作,但目前还不能: - (

编辑:以下是我的表格示例:

 ______________________________________________________________________________
| closure date | count of incidents closed | count of incidents remaining open |
|--------------|---------------------------|-----------------------------------|
| 01-Sep-12    | 5                         | 14                                |
| ...          | ...                       | ...                               |

会给出表格:

SELECT COUNT(incident_id)
WHERE closure_date IS NOT NULL AND status="open"
GROUP BY closure_date

3 个答案:

答案 0 :(得分:1)

SELECT 
COUNT(*) as closed,
(SELECT COUNT(t2.incident_id) FROM TABLE t2 WHERE t2.status = 'open' and t2.raised_date < t1.closure_date) as open
FROM TABLE t1
WHERE 
t1.status = 'closed'
GROUP BY t1.closure_date

或同样的想法

WITH opened AS (SELECT COUNT(t2.incident_id) as cnt FROM table t2 WHERE STATUS = 'open' )
SELECT 
   to_char(closure_date, 'yyyy/mm/dd') as dte
   count(*) as closed,
   opened.cnt as opens
FROM table, opened
WHERE status = 'closed'
GROUP BY to_char(closure_date, 'yyyy/mm/dd'), opened.cnt

答案 1 :(得分:1)

在我看来,对于每个日期,您希望获得迄今为止已关闭的问题数量以及日期之前提出的仍未解决的问题数量,正确?所以你可能想要这样的东西:

SELECT t1.closure_date, COUNT(t1.incident_id)
     , ( SELECT COUNT(t2.incident_id) FROM incident_table t2
          WHERE t2.status = 'open'
            AND t2.raised_date < t1.closure_date )
  FROM incident_table t1
 WHERE t1.closure_date IS NOT NULL
   AND t1.status = 'closed'
 GROUP BY t1.closure_date

答案 2 :(得分:0)

你应该尝试这样的事情:

SELECT 
closure_date,
SUM(CASE WHEN status="open" 
         THEN 1 ELSE 0 END) AS "count of incidents open",
SUM(CASE WHEN  status="closed" 
         THEN 1 ELSE 0 END) AS "count of incidents closed"
FROM YourTable
WHERE closure_date IS NOT NULL
GROUP BY closure_date