2016-03-29 108 views
0

我有一個表1:加入不同的列名和同一行的兩個表

|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  | 

我想結合r結果如下:

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

如何編寫SQL?

回答

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 
+0

感謝,這作品〜但有沒有辦法直接加入兩個結果?因爲某些列需要使用SUM()方法 – teejoe

+0

@teejoe你的意思是加入問題的兩個查詢,因爲它們是? –

+0

*** @ teejoe ***:你也可以在查詢中多次使用*'case' *並且可以和*'sum' * ... –

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; 
相關問題