按日期和类别将数据放入聚合存储桶

时间:2018-07-09 20:56:00

标签: sql oracle

我正在尝试按日期和类别显示已打开和已关闭的IT票证的总数。

父表包含以下列:

Alert_ID     Alert_Open_Date     Alert_Closed_Date

我希望我的最终结果类似于以下内容

A。任何指定日期范围内的日期

B。截至该日期仍显示为打开状态的警报总数(Outstanding_Alerts),

C。当天打开的警报总数(New_Alerts),

D。在该日期关闭的新警报总数(Closed_New_Alerts),并且

E。在该日期关闭的新警报和旧警报的总数量(Closed_Total):

  Date     Outstanding_Alerts     New_Alerts     Closed_New_Alerts     Closed_Total
6/1/2018       20                      10             5                     7
6/2/2018       23                      20             8                     10
6/3/2018       33                      13             10                    15
  etc.         #                       #              #                     #

我正在考虑使用类似以下概念性查询的方法来完成此操作,但是我在逻辑上绊脚石以获得所需的结果。无论措辞如何,我似乎都无法正确理解。例如,某些列在应填充时仍为空白。任何帮助表示赞赏。

SELECT DISTINCT
    alert_date
  , SUM(OOA)                AS Outstanding_Open_Alerts
  , SUM(NOA)                AS New_Open_Alerts
  , SUM(CNA*NOA)            AS Closed_New_Alerts
  , SUM(CT)                 AS Total_Closed_Alerts
  , SUM(CNA+NOA-CT)         AS Remaining_Alerts  --optional column

 FROM

 (SELECT
      TRUNC(open_date) AS Alert_Date
    , CASE WHEN alert_date < trunc(SYSDATE)-1 AND closed_date IS NULL THEN 1 ELSE 0
            END AS      OOA     --old open alerts
    , CASE WHEN alert_date > trunc(SYSDATE)-1 THEN 1 ELSE 0
            END AS      NOA     --new open alerts
    , CASE WHEN closed_date >= trunc(SYSDATE)-1 THEN 1 ELSE 0
            END AS      CNA     --closed new alerts
    , CASE WHEN closed_date < trunc(SYSDATE)-1 THEN 1 ELSE 0
            END AS      CT      --closed total
    FROM sys_alerts)

GROUP BY alert_date;

1 个答案:

答案 0 :(得分:0)

如果我按照您的描述,要获取以some_date形式提供的任意日期的数字,则需要以下内容:

SELECT
    some_date AS Alert_Date
  , COUNT(CASE WHEN open_date < some_date
      AND (closed_date IS NULL OR closed_date > some_date
      THEN alert_id END) AS Current_Open_Alerts
  , COUNT(CASE WHEN open_date >= some_date
      AND open_date < some_date + 1
      THEN alert_id END AS New_Alerts
  , COUNT(CASE WHEN open_date >= some_date
      AND open_date < some_date + 1
      AND closed_date < some_date + 1
      THEN alert_id END AS Closed_New_Alerts
  , COUNT(CASE WHEN closed_date >= some_date
      AND closed_date < some_date + 1
      THEN alert_id END AS Closed_Total
  , COUNT(CASE WHEN open_date < some_date + 1
      AND (closed_date IS NULL OR closed_date >= some_date + 1
      THEN alert_id END) AS Alerts_Remaining
FROM sys_alerts
GROUP BY some_date

我使用了一个计数而不是一个总和,这取决于计数忽略空值的事实-并在情况表达式中将默认值保留为空值。确实不需要sunquery,所以我将其删除。

似乎您希望所有数据都具有某个日期范围,因此可以在内联视图或CTE中生成该数据,然后将其连接到实际表中,因此some_date成为该生成范围内的各个日期。例如。得到最近30天的信息:

FROM (
    SELECT sysdate - level AS some_date
    FROM dual
    CONNECT BY level <= 30
LEFT JOIN sys_alerts
ON closed_date IS NULL OR closed_date >= some_date
GROUP BY some_date
ORDER BY some_date

或者您可以使用cross apply或分区外部联接来执行某些操作。希望这可以为您提供一个起点。