Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL将行转换为列,复杂类型_Sql_Sqlite_Pivot - Fatal编程技术网

SQL将行转换为列,复杂类型

SQL将行转换为列,复杂类型,sql,sqlite,pivot,Sql,Sqlite,Pivot,我需要把这张桌子换成这张桌子。。。这是一种旋转桌子的方法 我的桌子 year state Bar Rest disco grocery pharmacy 1945 CAL 220530236 9282364 0 3202436 0 1950 CAL 245988038 12181674 0 0 0 1955 CAL

我需要把这张桌子换成这张桌子。。。这是一种旋转桌子的方法

我的桌子

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

这是一个取消pivot/pivot操作。在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;