将2个表作为输入 - 员工和薪水为
Employee Salary
ID Name ID Salary
1 Anshika 1 1000
2 Arnav 2 2000
3 Ishita 3 3000
4 Iti 4 4000
将输出显示为 -
A I
3000 7000
我已将2个查询写为 -
mysql> select sum(salary) as sumA from salEmp where id in (select id from nameEmp where name LIKE 'A%');
output
sumA
3000
1行(0.00秒)
mysql> select sum(salary) as sumI from salEmp where id in (select id from nameEmp where name LIKE 'I%');
output
sumI
7000
1行(0.01秒)
但我想编写一个查询,以便我可以在问题中获得所需的输出。
我试过了 -
mysql> select sum(a.salary) as sumA, sum(b.salary) as sumI
-> from salEmp a,salEmp b
-> where a.id in
-> (select id from nameEmp where name LIKE 'A%')
-> AND b.id in
-> (select id from nameEmp where name LIKE 'I%');
但输出如下 -
sumA sumI
6000 14000
1 row in set (0.00 sec)
价值加倍 PLZ有助于获得原始输出...
答案 0 :(得分:0)
你正在做cross join。因此结果表获得重复值。 相反,您可以按照以下查询:
SELECT
SUM(CASE WHEN ID IN (SELECT ID FROM nameEmp
WHERE name Like 'A%') THEN Salary ELSE 0 END) AS sumA,
SUM(CASE WHEN ID IN (SELECT ID FROM nameEmp
WHERE name Like 'I%') THEN Salary ELSE 0 END) AS sumI
FROM salEmp
您可以了解" CASE WHEN"如果您对此不熟悉,请从这里开始。
http://www.java2s.com/Code/SQL/Flow-Control/UseCASEWHENstatementinSELECT.htm
答案 1 :(得分:0)
感谢您的帮助!!!我找到了另一个问题的解决方案 -
select a.sumA, b.sumI from
(select sum(salary) as sumA from salEmp where id in (select id from nameEmp where name LIKE 'A%')) a,
(select sum(salary) as sumI from salEmp where id in (select id from nameEmp where name LIKE 'I%')) b;