在单列中连接具有多列结果的表

时间:2017-01-18 11:08:35

标签: mysql sql database join conditional-statements

我有两张桌子 国家/地区表

id name 
1  Nepal
2  India

薪资表

id  Countryid termid amount
1    1         1      100
1    1         2      500
3    2         1      200
4    2         2      400

我希望结果为

CountryName basicSalary  allowance
Nepal       100          500
India       200          400

这里的第1项是基本工资,2是津贴

2 个答案:

答案 0 :(得分:2)

您可以尝试以下查询

SELECT c.name, 
    SUM(CASE WHEN s.termid = 1 THEN amount ELSE 0 END) basicSalary, 
    SUM(CASE WHEN s.termid = 2 THEN amount ELSE 0 END) allowance 
FROM Country c
JOIN Salary s on c.id = s.Countryid
GROUP BY c.name;

希望这会帮助你。

答案 1 :(得分:1)

只需加入桌子两次(使用别名)

select c.name as CountryName, 
       s1.amount as basicSalary
       s2.amount as allowance
from Country c
left join Salary s1
on s1.countryid=c.id
and s1.termid = 1

left join Salary s2
on s2.countryid=c.id
and s2.termid = 2