我需要将此表转换为该表...这是一种旋转表的方式。
我的桌子
year state Bar Rest disco grocery pharmacy
1945 CAL 220530236 9282364 0 3202436 0
1950 CAL 245988038 12181674 0 0 0
1955 CAL 268003540 10666664 0 180346 0
1945 NYC 21063922 353380 0 230132 0
1950 NYC 24450958 359908 4012 224012 2006
1955 NYC 27939064 434320 2006 893216 1003
我需要什么
State Type 1945 1950 1955
CAL Bar 220530236 245988038 268003540
CAL Rest 9282364 12181674 10666664
CAL disco 0 0 0
CAL grocery 3202436 0 180346
CAL pharmacy 0 0 0
NYC Bar 21063922 24450958 27939064
NYC Rest 353380 359908 434320
NYC disco 0 4012 2006
NYC grocery 230132 224012 893216
NYC pharmacy 0 2006 1003
答案 0 :(得分:0)
这是不可透视/枢轴操作。在SQLite中,可以使用union all
和条件聚合:
select state, type,
max(case when year = 1945 then val end) as val_1945,
max(case when year = 1950 then val end) as val_1950,
max(case when year = 1955 then val end) as val_1955
from (select year, state, 'bar' as type, bar as val
from t
union all
select year, state, 'rest' as type, rest as val
from t
union all
select year, state, 'disco' as type, disco as val
from t
union all
select year, state, 'grocery' as type, grocery as val
from t
union all
select year, state, 'pharmacy' as type, pharmacy as val
from t
) t
group by state, type
order by state, type;