SQL具有多个条件的多个计数列

时间:2018-04-06 14:50:25

标签: sql count

我正在尝试从表格中收集一些基本的统计数据" Data_Table"每天都会更新。每行代表一个案例,可由具有唯一ID的操作员打开/关闭/取消。我希望能够显示每位运营商前一天所做的操作的计数。从Data_Table到Ideal表。

Data_Table

|  LOCATION |   DATE   | REFERENCE | OPENED_ID | CLOSED_ID | CANCELLED_ID  |
|    NYC    | 20180102 |  123451   |    123    |    234    |      0        |
|    TEX    | 20180102 |  123452   |    345    |    123    |      0        |
|    NYC    | 20180102 |  123453   |    345    |     0     |     123       |
|    TEX    | 20180102 |  123453   |    234    |     0     |     123       |

理想表

|  LOCATION |   DATE   | USER_ID | OPEN | CLOSED | CANCELLED  |
|    NYC    | 20180102 |  123    |  1   |   0    |     1      |  
|    NYC    | 20180102 |  234    |  0   |   1    |     0      |
|    NYC    | 20180102 |  345    |  1   |   0    |     0      |
|    TEX    | 20180102 |  123    |  0   |   1    |     1      |
|    TEX    | 20180102 |  234    |  1   |   0    |     0      |
|    TEX    | 20180102 |  345    |  1   |   0    |     0      |

用户123打开了1个案例,并在20180102 ......等地点取消了纽约市的1个案例。

我为每个网站中的每个操作做了一些小查询,如下所示:

SELECT LOCATION, DATE, OPENED_ID, COUNT(DISTINCT [DATA_TABLE].REFERENCE)
FROM [DATA_TABLE]
WHERE DATE = CONVERT(DATE,GETDATE()-1)
AND LOCATION = 'NYC'
AND OPENED_ID in (SELECT NYC FROM [OP_ID_TABLE]WHERE [DATE FINISH] > GETDATE() )
GROUP BY OPENED_ID, LOCATION, DATE
ORDER BY LOCATION

然后对每个操作员操作的每个位置重复此查询。之后我在excel中做了一些凌乱的vlookup,将它组织成Ideal表格格式,每天都是...不理想。

我试图做一些总和功能,但没有运气。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您需要展开并重新聚合。一种方法使用union allgroup by

select location, date, user_id,
       sum(opened) as opens, sum(closed) as closes, sum(cancelled) as cancels
from ((select location, date, opened_id as user_id, 1 as opened, 0 as closed, 0 as cancelled
       from t
      ) union all
      (select location, date, closed_id as user_id, 0 as opened, 1 as closed, 0 as cancelled
       from t
      ) union all
      (select location, date, cancelled_id as user_id, 0 as opened, 0 as closed, 1 as cancelled
       from t
      )
     ) t
group by location, date, user_id;

根据数据库的不同,还有其他方法可以执行这些操作。但是,这是ANSI标准语法。