mysql组总和相同table
mysql group sum same table
我有以下 table:
id
name
type
score
1
john
orange
2345
2
john
yellow
5
3
john
black
5454540
4
jack
orange
1123
5
jack
yellow
1000
6
jack
black
86943
7
jane
orange
9876
8
jane
yellow
10000
9
jane
black
102233
评论;
id : inte
name : same name save more times to more rows,
score: it is int data
type : it has string data black,white,yellow,purple,orange
我正在使用以下查询来计算两个总分
SELECT name,sum(score) as `first`
FROM salary
WHERE type = 'orange'
SELECT name,sum(score) as `second`
FROM salary
WHERE type in ('black','yellow')
我想看到结果(所有名称必须是组,单个名称。)
name
FirstScore
SecondScore
john
2345
5454545
jack
1123
87943
jane
9876
112233
类似这样的东西(但这是未经测试的):
SELECT
salary.name,
first.score as "first_score",
second.score as "second_score"
FROM salary
LEFT JOIN (SELECT name,sum(score) as score
FROM salary
WHERE type = 'orange'
) as first ON first.name = salary.name
LEFT JOIN (SELECT name,sum(score) as score
FROM salary
WHERE type in ('black','yellow')
) as second ON second.name = salary.name
使用条件 SUM() 聚合基于 type
的值:
SELECT name
, SUM(CASE WHEN type IN ('orange') THEN score END ) AS FirstScore
, SUM(CASE WHEN type IN ('yellow','black') THEN score END ) AS SecondScore
FROM salary
GROUP BY Name
结果:
name
FirstScore
SecondScore
john
2345
5454545
jack
1123
87943
jane
9876
112233
db<>fiddle here
我有以下 table:
id | name | type | score |
---|---|---|---|
1 | john | orange | 2345 |
2 | john | yellow | 5 |
3 | john | black | 5454540 |
4 | jack | orange | 1123 |
5 | jack | yellow | 1000 |
6 | jack | black | 86943 |
7 | jane | orange | 9876 |
8 | jane | yellow | 10000 |
9 | jane | black | 102233 |
评论;
id : inte
name : same name save more times to more rows,
score: it is int data
type : it has string data black,white,yellow,purple,orange
我正在使用以下查询来计算两个总分
SELECT name,sum(score) as `first`
FROM salary
WHERE type = 'orange'
SELECT name,sum(score) as `second`
FROM salary
WHERE type in ('black','yellow')
我想看到结果(所有名称必须是组,单个名称。)
name | FirstScore | SecondScore |
---|---|---|
john | 2345 | 5454545 |
jack | 1123 | 87943 |
jane | 9876 | 112233 |
类似这样的东西(但这是未经测试的):
SELECT
salary.name,
first.score as "first_score",
second.score as "second_score"
FROM salary
LEFT JOIN (SELECT name,sum(score) as score
FROM salary
WHERE type = 'orange'
) as first ON first.name = salary.name
LEFT JOIN (SELECT name,sum(score) as score
FROM salary
WHERE type in ('black','yellow')
) as second ON second.name = salary.name
使用条件 SUM() 聚合基于 type
的值:
SELECT name
, SUM(CASE WHEN type IN ('orange') THEN score END ) AS FirstScore
, SUM(CASE WHEN type IN ('yellow','black') THEN score END ) AS SecondScore
FROM salary
GROUP BY Name
结果:
name | FirstScore | SecondScore |
---|---|---|
john | 2345 | 5454545 |
jack | 1123 | 87943 |
jane | 9876 | 112233 |
db<>fiddle here