我有下表:
| ID | 姓名 | 型別 | 分數 |
|---|---|---|---|
| 1 | 約翰 | 橘子 | 2345 |
| 2 | 約翰 | 黃色的 | 5 |
| 3 | 約翰 | 黑色的 | 5454540 |
| 4 | 杰克 | 橘子 | 1123 |
| 5 | 杰克 | 黃色的 | 1000 |
| 6 | 杰克 | 黑色的 | 86943 |
| 7 | 簡 | 橘子 | 9876 |
| 8 | 簡 | 黃色的 | 10000 |
| 9 | 簡 | 黑色的 | 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')
我想看到結果(所有名稱必須是組,單個名稱。)
| 姓名 | 第一分數 | SecondScore |
|---|---|---|
| 約翰 | 2345 | 5454545 |
| 杰克 | 1123 | 87943 |
| 簡 | 9876 | 112233 |
uj5u.com熱心網友回復:
使用條件 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
結果:
| 姓名 | 第一分數 | SecondScore |
|---|---|---|
| 約翰 | 2345 | 5454545 |
| 杰克 | 1123 | 87943 |
| 簡 | 9876 | 112233 |
db<>在這里擺弄
uj5u.com熱心網友回復:
像這樣的東西(但這是未經測驗的):
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457346.html
