简体   繁体   English

带有多个选择语句的MYSql子查询

[英]MYSql Sub Query with multiple select statement

I've got a table that looks like this 我有一张桌子,看起来像这样

Savings
ID | Name | Type | Amount | Date
1  | Alex | Cash | 100    | 2019-06-10
2  | Nick | CHQ  | 500    | 2019-06-10
3  | Mike | Cash | 700    | 2019-06-10
4  | Luke | CHQ  | 200    | 2019-06-10
5  | Alex | Card | 300    | 2019-06-10
6  | Alex | Card | 100    | 2019-06-10
7  | Luke | Cash | 900    | 2019-06-10
8  | Alex | Cash | 400    | 2019-06-10
9  | Mike | CHQ  | 200    | 2019-06-10

is it possible to sort it out in this manner using only 1 select statement? 是否可以仅使用1条select语句以这种方式进行分类?

Final Output
Name | Total Amount | Total Cash | Total Chq
Mike | 900          | 700        | 200
Luke | 1100         | 900        | 200
Alex | 500          | 500        | 0
Nick | 500          | 0          | 500

This is my current statement 这是我目前的说法

SELECT 
  name, 
  SUM(amount) 
FROM 
  savings 
WHERE 
  date = '2019-06-10' AND 
  type = 'Cash' OR date = '2019-06-10' AND 
  type = 'Chq' 
GROUP BY 
  name 
ORDER BY 
  SUM(amount) DESC

All help appreciated. 所有帮助表示赞赏。 thanks 谢谢

use conditional aggregation with case when expression case when expression使用conditional aggregation

SELECT name, sum(amount) as 'Total Amount',
SUM(case when type = 'Cash' then amount end) as 'Total Cash',
SUM(case when type = 'Chq' then amount end) as 'Total Chq'
FROM savings 
where date = '2019-06-10' group BY name 

For example: 例如:

select 
    Name,
    sum(Amount) 'Total Amount',
    sum(if(Type = 'Cash', Amount, 0)) 'Total Cash',
    sum(if(Type = 'CHQ', Amount, 0)) 'Total Chq'
from savings 
group by Name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM