如何根据分组条件将多个行分组到一组列中?
例如,
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
向
ID Deduction Safety
==========================================
36197 -9 0
36200 -1 -1
36337 1 0
36363 0 0
36364 0 1
36342 0 0
36350 0 10
答案 0 :(得分:5)
您可以使用案例陈述来有条件地汇总:
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
答案 1 :(得分:0)
SELECT DISTINCT ID, (SELECT TOTAL FROM TABLE AS A WHERE A.ID = X.ID AND A.TYPE = 'DEDUCTION') AS DEDUCTION,(SELECT TOTAL FROM TABLE AS B WHERE B.ID = X.ID AND B.TYPE = 'SAFETY') AS SAFETY
FROM TABLE AS X;
答案 2 :(得分:0)
您也可以使用pivot解决。
select * from tableA
pivot (
max(total) for type in (Deduction, Safety)
) as pvt