如何计算SQL

时间:2016-03-20 13:26:30

标签: sql sql-server oracle

我有一个如下图表

+----------------------------------------------------------+
|  ID | REGION | STATUS | CLOSED_DT |HEALTH  | Open_DT     |
+----------------------------------------------------------+
|   1 | QA     | open   |  -        |  red   | 2016-01-03  |
|   2 | QA     | open   |  -        | green  | 2015-03-03  |
|   3 | QA     | open   |  -        | orange | 2016-02-03  |
|   4 | QA     | open   |  -        | red    | 2016-01-03  |
|   5 | x      | closed |  16-03-03 | green  | 2015-06-03  |
|   6 | Req    | open   |  -        | orange | 2015-05-03  |
|   7 | x      | closed |  16-02-02 | green  | 2015-05-03  |
+----------------------------------------------------------+

我想显示三个图表 - 条形图,饼图,月份趋势图。第一张图表需要计算不同区域的开放状态。

  

选择区域,计数(*)为图表中的总数,其中STATUS ='打开'按地区分组;

我使用上面的条形图查询。对于饼图,我使用了以下查询

  

选择健康,计算(*)为图表中的总数,其中STATUS ='打开'按健康分组;

接下来是月度明智的图表,我需要显示过去12个月。例如从1月到12月,我需要每个月打开和关闭的数量。如何构建查询以获取当前日期过去12个月的打开和关闭状态计数。而不是为每个图表执行三个不同的查询,有没有办法使用单个查询。我需要查询Oracle和Mssql

1 个答案:

答案 0 :(得分:1)

您应该使用条件聚合:

SELECT to_char(Open_DT,'YYYY') as yearCol, to_char(Open_DT,'MM') as MonthCol,
       count(CASE WHEN status = 'open' then 1 end) as openCnt,
       count(CASE WHEN status = 'closed' then 1 end) as closeCnt
FROM YourTable
WHERE Open_DT >= add_months(sysdate,-13) 
GROUP BY to_char(Open_DT,'YYYY'),to_char(Open_DT,'MM')

您标记了sql-server和oracle,以上解决方案适用于oracle

对于sql server:

SELECT year(Open_DT) as yearCol, month(Open_DT) as MonthCol,
       count(CASE WHEN status = 'open' then 1 end) as openCnt,
       count(CASE WHEN status = 'closed' then 1 end) as closeCnt
FROM YourTable
WHERE Open_DT > DATEADD(month,-13,getdate())
GROUP BY year(Open_DT),month(Open_DT)