【问题标题】:sqlite query with multiple columns result具有多列结果的sqlite查询
【发布时间】:2020-09-09 22:15:43
【问题描述】:

我要取一个sqlite数据表:

Margin  Load  Volt
------  ----  ----
10      1     6.0
15      2     6.0
20      3     6.0
35      1     7.0
45      2     7.0
55      3     7.0
91      3     8.0
92      3     8.0
95      3     8.0

并创建新表:

Load  Margin6  Margin7  Margin8
----  -------  -------  -------
1     10       35       91  
2     15       45       92
3     20       55       95

我不知道如何实现。

【问题讨论】:

    标签: sql sqlite group-by pivot


    【解决方案1】:

    你可以做条件聚合:

    select 
        load,
        max(case when volt = 6 then margin end) margin6,
        max(case when volt = 7 then margin end) margin7,
        max(case when volt = 8 then margin end) margin8
    from mytable
    group by load
    

    如果要使用查询结果创建表,可以选择使用create table ... as select ... 语法:

    create table newtable as
    select 
        load,
        max(case when volt = 6 then margin end) margin6,
        max(case when volt = 7 then margin end) margin7,
        max(case when volt = 8 then margin end) margin8
    from mytable
    group by load
    

    我也不建议这样做,因为它没有给您定义约束、主键和其他相关元信息的空间。您也可以先create 表,然后用insert into ... select ... 语句提供它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2020-10-11
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多