gpt4 book ai didi

sql - 检查 PostgreSQL 中组查询中的单个行

转载 作者:行者123 更新时间:2023-11-29 11:48:29 26 4
gpt4 key购买 nike

WITH 
Emp(DName, EName, Role) AS (
VALUES ('D1','E11', 'Role1'),
('D1','E11', 'Role2'),
('D1','E12', 'Role1'),
('D2','E12', 'Role1')
)

对于每个部门,获取每个角色的员 worker 数。
输出应该是:

#_of_Role1_Employees; #_of_Role2_Employees
2; 1
1; 0

最佳答案

WITH 
Emp(DName, EName, Role) AS (
VALUES ('D1','E11', 'Role1'),
('D1','E11', 'Role2'),
('D1','E12', 'Role1'),
('D2','E12', 'Role1')
)
select
dname "Dname",
count(role = 'Role1' or null) "Role1",
count(role = 'Role2' or null) "Role2"
from emp
group by dname
;
Dname | Role1 | Role2
-------+-------+-------
D1 | 2 | 1
D2 | 1 | 0

更新

这应该符合不同的要求:

WITH
Emp(DName, EName, Role) AS (
VALUES ('D1','E11', 'Role1'),
('D1','E11', 'Role2'),
('D1','E12', 'Role1'),
('D2','E12', 'Role1')
)
select
dname "Dname",
count(role = 'Role1' or null) "Role1",
count(role = 'Role2' or null) "Role2"
from (
select distinct *
from emp
) s
group by dname
;
Dname | Role1 | Role2
-------+-------+-------
D1 | 2 | 1
D2 | 1 | 0

关于sql - 检查 PostgreSQL 中组查询中的单个行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14871888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com