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

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

#_of_Role1_Employees; #_of_Role2_Employees
2; 1
1; 0
4

3 回答 3

2
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
于 2013-02-14T10:32:06.053 回答
0

在部门组中,要检查每个员工行的角色,并对不同的员工姓名进行计数。

Select COUNT(Distinct(CASE WHEN Role = 'Role1' THEN EName END)) As "#_of_Role1_Employees",
       COUNT(Distinct(CASE WHEN Role = 'Role2' THEN EName END)) As "#_of_Role2_Employees"
from Emp
Group by DName
于 2013-02-14T09:46:27.070 回答
0

每个可以有重复条目的事实(dname, ename, role)表明测试用例过于简化。我怀疑测试用例应该是:

CREATE TEMP TABLE emp(dname text, ename text, role text, col1 text);
INSERT INTO emp VALUES
    ('D1','E11', 'Role1', 'foo1')
   ,('D1','E11', 'Role2', 'foo2')
   ,('D1','E12', 'Role1', 'foo3')
   ,('D1','E12', 'Role1', 'foo4')
   ,('D2','E12', 'Role2', 'foo5');

然后@Clodoaldo 的(否则很好)查询将不得不使用:

SELECT DISTINCT dname, ename, role

代替:

SELECT DISTINCT *

另一种方法是交叉表查询:

SELECT * FROM crosstab(
      $x$
      SELECT dname, role, count(DISTINCT ename)::int
      FROM   emp
      GROUP  BY dname, role
      $x$

      ,$y$SELECT DISTINCT role FROM emp ORDER BY 1$y$)
AS ct (dname text, "Role1" text, "Role2" int);

您需要tablefunc为此安装。此相关答案中有关此查询的更多详细信息:
PostgreSQL Crosstab Query

您必须在列定义列表中列出所有可能的角色。

于 2013-02-14T12:27:41.503 回答