Raj*_*ami 0 sql t-sql sql-server grouping
如何根据分组条件将多个行分组到一组列中?
例如,
ID Type Total
==============================
36197 Deduction -9
36200 Deduction -1
36337 Deduction 1
36363 Deduction 0
36364 Deduction 0
36200 Safety -1
36342 Safety 0
36350 Safety 10
36363 Safety 0
36364 Safety 1
Run Code Online (Sandbox Code Playgroud)
成
ID Deduction Safety
==========================================
36197 -9 0
36200 -1 -1
36337 1 0
36363 0 0
36364 0 1
36342 0 0
36350 0 10
Run Code Online (Sandbox Code Playgroud)
您可以使用case语句有条件地聚合:
select id,
sum(case when type = 'Deduction' then total else 0 end) as deduction,
sum(case when type = 'Safety' then total else 0 end) as safety
from tbl
group by id
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |