SQL修改列的顺序并从查询中添加新列

时间:2015-07-17 09:19:49

标签: python sql sqlite

如果可能的话,我想知道如何进行以下操作:

原始表的样本:

Type      Status    I1    I2    I3    I4    I5
 A          ON      3     4     2     10    2
 A         OFF      1     1     0     null  null
 B          ON      5     6     2     10    2
 B         OFF      2     1     2     null  null
 C          ON      8     7     5     10    2
 C         OFF      1     1     1     null  null
 A          ON      4     4     4     10    2
 A         OFF      2     2     1     null  null
 B          ON      5     4     5     10    2
 B         OFF      1     1     1     null  null

所以,基本上我想要的是以下列方式合并来自ION状态的OFF值:

根据上表,来自I1的{​​{1}},I2I3值将变为OFF statusI6,{{1输出将是

I7

要明确的是,它只会从每个I8的{​​{1}}中获取值Type I1 I2 I3 I4 I5 I6 I7 I8 A 3 4 2 10 2 1 1 0 B 5 6 2 10 2 2 1 2 C 8 7 5 10 2 1 1 1 A 4 4 4 10 2 2 2 1 B 5 4 5 10 2 1 1 1 I1I2并放置它们与I3 OFF statustypeON status

的结果一起显示

2 个答案:

答案 0 :(得分:2)

如果您id列自动递增它没有间隙,那么您可能很幸运

select o1.*, o2.i1 as i6, o2.i2 as i7, o2.i3 as i8
from original o1 join
     original o2
     on o2.id = o1.id + 1 and
        o2.type = o1.type and
        o1.status = 'ON' and o2.status = 'OFF';

否则,此查询比看起来要困难得多。您需要对类似的id进行分组。一种方法是通过具有相同类型和ON的相似行的数量来识别它们。您可以使用相关子查询来获取此信息:

with o as (
      select o.*,
             (select count(*)
              from original o2
              where o2.type = o.type and o2.status = 'ON' and o2.id <= o.id
             ) as grp
      from original o
     )
select o.type,
       max(case when type = 'ON' then i1 end) as i1,
       max(case when type = 'ON' then i2 end) as i2,
       max(case when type = 'ON' then i3 end) as i3,
       max(case when type = 'ON' then i4 end) as i4,
       max(case when type = 'ON' then i5 end) as i5,
       max(case when type = 'OFF' then i1 end) as i6,
       max(case when type = 'OFF' then i2 end) as i7,
       max(case when type = 'OFF' then i3 end) as i8
from o
group by grp, type ;

答案 1 :(得分:0)

试试这个:

SELECT Type, SUM(I1) AS I1, SUM(I2) AS I2, SUM(I3) AS I3, SUM(I4) AS I4, SUM(I5) AS I5, SUM(I6) AS I6, SUM(I7) AS I7, SUM(I8) AS I8
FROM (
    SELECT Type, I1, I2, I3, I4, I5, 0 As I6, 0 As I7, 0 As I8
    FROM YourTable
    WHERE Status = 'ON'
    UNION ALL
    SELECT Type, 0 , 0, 0, 0, 0, I1 As I6, I2 As I7, I3 As I8
    FROM YourTable
    WHERE Status = 'OFF') DT
GROUP BY Type