连接具有不同列名和相同行的两个表

时间:2016-03-29 08:15:53

标签: mysql sql

我有一个table1:

|age  | name   | sex  | money |
-------------------------------
|20   | James  | 1    | 1000  |
|20   | Marry  | 2    | 2000  |
|20   | Kate   | 2    | 1500  |
|20   | Parker | 1    | 1800  |

我有两个查询结果:

1:

select `age`, count(*) as `man`, sum(money) as man_money
from table1
where `sex` = 1 and age = 20;

|age| man   | man_money |
-------------------------
|20 | 2     | 2800      |

2:

select `age`, count(*) as `woman`, sum(money) as woman_money
from table1
where `sex` = 2 and age = 20;

|age |woman   | woman_money |
-----------------------------
|20  |2       | 3500        |

我想结合如下结果:

|age | man   | woman  | man_money | woman_money |
--------------------------------------------------
|20  | 2     | 2      | 2800      | 3500        |

如何编写SQL?

2 个答案:

答案 0 :(得分:0)

试试这个:

select age, 
       count(case when sex = 1 then 1 end) as man,
       count(case when sex = 2 then 1 end) as woman,
       sum(case when sex = 1 then money end) as man_money,
       sum(case when sex = 2 then money end) as woman_money
from table1
where age = 20

答案 1 :(得分:0)

我不知道Mysql,但是因为我的知识sql对于所有数据库都是一样的,我在oracle中尝试过它可以根据需要使用

select age, 

       count(case when sex = 1 then 1 end) as man,

       count(case when sex = 2 then 1 end) as woman

from table1 group by age;