SQL 具有多个条件的多个计数列
Posted
技术标签:
【中文标题】SQL 具有多个条件的多个计数列【英文标题】:SQL Multiple count columns with multiple conditionS 【发布时间】:2018-04-06 14:50:25 【问题描述】:我正在尝试从每天更新的表“Data_Table”中收集一些基本统计信息。每行代表一个案例,可由具有唯一 ID 的操作员打开/关闭/取消。我希望能够显示每个操作员前一天执行的操作的计数。所以从 Data_Table 到 Ideal 表。
数据表
| 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 于日期 20180102...等在 NYC 开了 1 个案例并取消了 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 中进行了一些凌乱的 vlookups 以将其组织成理想的表格格式,这在日常的基础上是..不理想的。
我尝试了一些求和函数,但没有任何运气。
任何帮助将不胜感激。
【问题讨论】:
用您正在使用的数据库标记您的问题。 【参考方案1】:您需要取消透视并重新聚合。一种方法使用union all
和group 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 标准语法。
【讨论】:
以上是关于SQL 具有多个条件的多个计数列的主要内容,如果未能解决你的问题,请参考以下文章