sqlite 透视单行 Dataframe ,使列标题和值都成为列中的值

nafvub8i  于 2023-02-16  发布在  SQLite
关注(0)|答案(1)|浏览(147)

我在SQLite中有一个如下所示的表:
| 住房|家具|庭院工程|
| - ------|- ------|- ------|
| 22.2 |五、二|三、六|
我想旋转它,使它看起来如下所示:
| 任务|时间|
| - ------|- ------|
| 住房|二十二、二|
| 家具|五、二|
| 庭院工程|三、六|
我如何在SQLite中做到这一点,而不显式列出每个列名?

w7t8yxp5

w7t8yxp51#

可以使用CROSS JOIN执行此操作,如下所示:

select 
  c.col as Task,
  case c.col
    when 'Housing' then Housing
    when 'Furniture' then Furniture
    when 'YardWork' then YardWork
  end as Time
from mytable t
cross join
(
  select 'Housing' as col
  union all select 'Furniture'
  union all select 'YardWork'
) c

此处仅列出一列:

select 
      c.col as Task,
      case c.col
        when 'Housing' then Housing
      end as Time
    from mytable t
    cross join
    (
      select 'Housing' as col
    ) c

Demo here

相关问题