sql - 通过包含零将多个计数与组组合
问题描述
我有 3 个表:设备、部分和用户,我想组合按部分分组的 3 个表,并显示每个部分的总设备和每个部分的总用户数,包括零
Example equipment table:
ID Device Name SectionID Device Type
1 Holly's computer 1 PC
2 John's mobile 2 mobile
3 Maggie's printer 3 printer
4 Jonathan's scanner 3 scanner
5 George's scanner 2 scanner
6 Dugans handheld 5 scanner
7 Main printer 5 printer
Example sections table:
ID Section
1 Finance
2 HR
3 IT
4 Manager
5 Storage
Example users table
ID User SectionID
1 John 3
2 George 2
3 Amanda 2
4 Andy 4
5 Katherine 1
我试过这个:
SELECT
b.section AS GROUPED_SECTION,
COUNT(distinct a.sectionid) AS TOTAL_EQUIPMENT,
COUNT(distinct c.sectionid) AS TOTAL_USERS
FROM Equipment a
LEFT JOIN Section b ON a.sectionid=b.id
LEFT JOIN Users c on a.sectionid=c.sectionid
GROUP BY b.description
ORDER BY b.description
但有些东西不能正常工作
我想创建一个具有以下结果的查询:
SECTION TOTAL_EQUIPMENT TOTAL_USERS
------- --------------- ------------
Finance 1 1
IT 2 1
HR 2 2
Manager 0 1
Storage 2 0
-1 列显示与设备表不同的部分
-2 列根据设备表显示每个部分的总设备
-3 列根据用户表显示该部分下的总用户
解决方案
用于on和UNION ALL
表。并制作一列来拆分两个不同的表。SectionID
equipment
users
grp
然后做OUTER JOIN
基于sections
表,最终使用聚合函数获取计数。
查询 1:
SELECT s.Section,
COUNT(CASE WHEN grp = 1 THEN 1 END) TOTAL_EQUIPMENT,
COUNT(CASE WHEN grp = 2 THEN 1 END) TOTAL_USERS
FROM sections s
LEFT JOIN (
select SectionID,1 grp
from equipment
UNION ALL
select SectionID,2 grp
from users
) t1 on t1.SectionID = s.ID
GROUP BY s.Section
结果:
| Section | TOTAL_EQUIPMENT | TOTAL_USERS |
|---------|-----------------|-------------|
| Finance | 1 | 1 |
| HR | 2 | 2 |
| IT | 2 | 1 |
| Manager | 0 | 1 |
| Storage | 2 | 0 |
推荐阅读
- c# - 带静态类的循环引用项目
- python - (1064, "您的 SQL 语法有错误;.. 在第 1 行的 '%s, %s, %s, %s, %s)' 附近使用正确的语法")
- javascript - 如何在两者之间渲染 JSX 代码
标签
- c# - Entity Framework 6 Code First - 将函数或 StoredProc 映射到原始类型
- jq - jq - 返回所有具有匹配条件的子属性的顶级属性键
- javascript - Javascript .getJSON 多个 URL
- jenkins - jenkins 上的 JIRA 插件未设置 JIRA_ISSUES 变量
- python - 如何在python中腌制命名空间
- wpf - 滚动时触发 DataGrid SelectionChanged 事件
- python - Pandas:匿名 client_id 列,没有任何回滚的可能性