假設我有一張這樣的桌子:
id | amount
-------------------------
1 | 10
1 | 10
2 | 20
2 | 10
3 | 20
3 | 10
3 | 10
4 | 10
假設 id 1和2是特殊的,我想將它們組合在一起并將其命名為special。1和2以外的 ID也不應組合在一起。最后,我想總結一下金額。那么,我如何得到這樣的結果:
type | total_amount
-------------------------------
special | 50
3 | 40
4 | 10
uj5u.com熱心網友回復:
您可以使用 acase when將id的值轉換為您所追求的值,然后應用一個sum()函式來獲取聚合:
select
case
when id in (1, 2) then 'special'
else cast(id as char)
end as type,
sum(amount) as total_amount
from <your_table>
group by 1
uj5u.com熱心網友回復:
請試試這個
SELECT
CASE
WHEN id IN (1, 2) THEN 'special'
ELSE CAST(id AS CHAR)
END AS type,
SUM(amount) AS total_amount
FROM __table__
GROUP BY id
uj5u.com熱心網友回復:
您還可以使用以下代碼分別查看每個特殊 ID:
select case
when id in (1, 2) then 'Special'
else id
end type,
id,
sum(amount) total_amount
from table
group by 1,2
| 型別 | ID | 數量 |
|---|---|---|
| 特別的 | 1 | 20 |
| 特別的 | 2 | 30 |
| 3 | 3 | 40 |
| 4 | 4 | 10 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/520391.html
標籤:mysqlsql数据库
上一篇:如何從自聯接表中檢索空值
