我想展示每个部门的文员和经理人数。
这是我的代码:
SELECT DISTINCT
deptno AS 'DEPARTMENT NUMBER',
(SELECT COUNT(*)
FROM EMP
WHERE JOB = 'CLERK'
GROUP BY DEPTNO) AS 'NUMBER OF CLERKS',
(SELECT COUNT(*)
FROM EMP
WHERE JOB = 'MANAGER'
GROUP BY DEPTNO) AS 'NUMBER OF MANAGER'
FROM
EMP
GROUP BY
deptno
以下是返回的错误:
子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。
我想像这样显示结果:
+-------------------+------------------+---------------------+
| DEPARTMENT NUMBER | NUMBER OF CLERKS | NUUMBER OF MANAGERS |
+-------------------+------------------+---------------------+
| 10 | 1 | 1 |
| 20 | 2 | 1 |
| 30 | 1 | 1 |
+-------------------+------------------+---------------------+
答案 0 :(得分:1)
这种计算通常最容易使用sum
+ case
进行此类计算:
SELECT
deptno,
sum (case when JOB = 'CLERK' then 1 else 0 end) AS [NUMBER OF CLERKS],
sum (case when JOB = 'MANAGER' then 1 else 0 end) AS [NUMBER OF MANAGERS]
FROM
EMP
GROUP BY
deptno
答案 1 :(得分:0)
您也可以使用PIVOT
DECLARE @EMP table (Dep_No INT, Job VARCHAR(20))
INSERT INTO @EMP
VALUES (10,'clerk'),
(10,'clerk'),
(10,'clerk'),
(10,'Manager'),
(20,'clerk'),
(20,'clerk'),
(20,'clerk'),
(20,'clerk'),
(20,'clerk'),
(20,'clerk'),
(20,'Manager'),
(20,'Manager'),
(30,'clerk'),
(20,'Manager'),
(30,'clerk')
SELECT Dep_No , [clerk] Number_Of_Clerks ,[Manager] Number_of_Managers
FROM @EMP
PIVOT
(
COUNT(Job) FOR Job in ([clerk], [Manager])
) W