我试图从EMP表中显示一些数据,我想要实现的输出如下:
ENAME, SUM_SAL, AVG(SAL),MAX(SAL)
问题是我需要在每个组函数上添加一个where子句,例如:
SELECT ENAME, (SELECT SUM(COMM) FROM EMP WHERE EMPNO BETWEEN 7000 AND 7500) ,SELECT (AVG(COMM) FROM EMP WHERE EMPNO BETWEEN 7000 AND 7500), GROUP BY ENAME
这不起作用
答案 0 :(得分:1)
要根据每个员工姓名进行聚合,请写为:
SELECT ENAME,
SUM(COMM),
AVG(COMM)
FROM EMP
WHERE EMPNO BETWEEN 7000 AND 7500
GROUP BY ENAME
要根据表中的员工进行聚合,请写为:
SELECT ENAME,
SUM(COMM) OVER (ORDER BY EMPNO ASC) as sum_sal,
AVG(COMM) OVER (ORDER BY EMPNO ASC) as avg_sal,
MAX(COMM) OVER (ORDER BY EMPNO ASC) as MAX_sal
FROM @EMP
WHERE EMPNO BETWEEN 7000 AND 7500
答案 1 :(得分:1)
使用conditional Aggregate
SELECT ENAME,
Sum(CASE
WHEN EMPNO BETWEEN 7000 AND 7500 THEN COMM
ELSE 0
END) [Sum],
Avg(CASE
WHEN EMPNO BETWEEN 7000 AND 7500 THEN COMM
END) [Avg]
FROM EMP
GROUP BY ENAME
答案 2 :(得分:0)
尝试这样的事情:
SELECT ENAME, SUM(COMM), AVG(COMM)
FROM EMP
WHERE EMPNO BETWEEN 7000 AND 7500
GROUP BY ENAME
它会在{7000}到7500之间选择每个ENAME
EMPNO
,并为每个COMM
获取{{1}}的总和和平均值。