首页 > 解决方案 > 通过包含零将多个计数与组组合

问题描述

我有 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 列根据用户表显示该部分下的总用户

标签: sqlsql-serveraggregate-functions

解决方案


用于on和UNION ALL表。并制作一列来拆分两个不同的表。SectionIDequipmentusersgrp

然后做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 |

推荐阅读