簡體   English   中英

連接具有不同列名和相同行的兩個表

[英]Join two tables with different column names and same rows

我有一張桌子:

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

嘗試這個:

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

我不了解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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM