我有桌子( emp ):
我想获得第一列
第二栏
和第三栏
我能够获得第一列和第二列但无法获得具有相同查询的Thiird列:
SELECT DeptNo, SUM(Salary) AS 'Name Contains A', SUM(Salary) AS 'Total Salary'
FROM emp
WHERE Ename LIKE 'A%'
GROUP BY DeptNo
任何建议我该怎么做?
答案 0 :(得分:4)
如果您的DBMS支持del string.maketrans
,您可以执行以下操作:
CASE
这会产生
select
deptno,
sum(case when ename like 'A%' then salary else 0 end) as ASalary,
sum(salary) as AllSalaries
from
emp
group by
deptno
答案 1 :(得分:2)
您可以使用子查询执行此操作:
SELECT DeptNo, SUM(Salary) AS 'Name Contains A',
(SELECT SUM(Salary) FROM emp) AS 'Total Salary'
FROM emp
WHERE Ename LIKE 'A%'
GROUP BY DeptNo
答案 2 :(得分:0)
据我所知,SQL无法提出您所要求的内容,但您可以使用WITH ROLLUP
子句作为附加行获取查询中所有结果的总和:
SELECT DeptNo, SUM(Salary)
FROM emp
WHERE Ename LIKE 'A%'
GROUP BY DeptNo WITH ROLLUP
这将为您提供按部门划分的工资分组和一个额外的行,其中包含匹配部门的所有工资总和。
答案 3 :(得分:0)
您可以使用这样的子查询:
SELECT emp."DeptNo", SUM(emp."Salary") AS "Name Contains A", sum("DeptTotals"."DeptTotal")
FROM emp inner join (select "DeptNo", sum("Salary") as "DeptTotal"
from emp
group by "DeptNo"
) as "DeptTotals" on "DeptTotals"."DeptNo" = emp."DeptNo"
WHERE emp."Ename" LIKE 'A%'
GROUP BY emp."DeptNo"
因此,您将原始查询与子查询一起加入,该子查询包含同一部门的所有员工的总数。