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

标签 mysql sql

我有一个表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        |

我想合并如下结果:

|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 - 连接具有不同列名和相同行的两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36278890/

相关文章:

mysql - MySQL select 语句中的查询计数

mysql - 如何更新数据库中的日期间隔(Hibernate HQL)

mysql - 使用 PHPMyAdmin 导入 CSV 确实很麻烦

sql - 没有表格的映射值

sql - 如何停止 PostgreSQL 中正在运行的查询?

mysql - 选择多个 mysql 列

mysql - 如何获取SQL组合字段结果

php - 如何使用 CDbMigration 从表中删除键

c# - LINQ to SQL - 调用内置聚合函数(即 STDEV)

sql子查询分组依据