简体   繁体   English

SQL Unpivot表

[英]SQL Unpivot table

I am facing problem on unpivot sql statement, below is the table how its look like: 我在unpivot sql语句上遇到问题,下表是它的外观:

ID  A0001       A0002      A0003
==  =========== ========== ==========
S1  100         200        300 
S2  321         451        234
S3  0           111        222

I want to pivot A0001,A0002 and A0003. 我想旋转A0001,A0002和A0003。 Create 3 more column for HEADER,SEQUENCE AND DATA. 再为HEADER,SEQUENCE和DATA创建3列。 Below is my expected table to become like this: 下面是我期望的表格变成这样:

ID  HEADER      SEQUENCE     DATA
==  ==========  ===========  =======
S1  A0001       1            100 
S1  A0001       2            200
S1  A0001       3            300
S2  A0002       1            321
S2  A0002       2            451
S2  A0002       3            234
S3  A0003       1            111
S3  A0003       2            222

Below is the sql statement I have try: 以下是我尝试过的sql语句:

SELECT ID,DATA FROM
(SELECT ID,A0001,A0002,A0003 FROM STG.TABLE_A)
UNPIVOT
(DATA FOR B IN (A0001,A0002,A0003)) C

The SQL I write only allow to show the data after pivot, for HEADER and SEQUENCE field I have no idea how to write 我写的SQL只允许在数据透视后显示数据,对于HEADER和SEQUENCE字段我不知道如何写

Secondly, I would also like to filter out if any pivot column is zero will be filter out. 其次,我也想过滤掉是否任何枢轴列为零的情况。 Example, ID = S3, A0001 is 0,therefore filter the zero and only get other fields which is greater than zero 例如,ID = S3,A0001为0,因此过滤零并仅获取大于零的其他字段

You can have this condition after appling unpivot as below - 如下所示应用取消透视后,您可能会遇到这种情况-

SELECT ID, DATA, header
  FROM (SELECT ID, A0001, A0002, A0003 FROM STG.TABLE_A) 
        UNPIVOT(DATA FOR header IN (A0001, A0002, A0003)) C
 where data <> 0

You can either use the unvipot function or you can simply use union also in this case as below - 在这种情况下,您可以使用unvipot函数,也可以简单地使用union ,如下所示-

   select id, header, sequence, data
    from (select @i := if(@lastid != id, 1, $i + 1) as sequence,
           @lastid := id,
           id,
           header,
           data
      from (

            select ID, 'A0001' as Header, A0001 as DATA
              from your_table_name
             where A0001 <> 0
            union all
            select ID, 'A0002' as Header, A0002 as DATA
              from your_table_name
             where A0002 <> 0
            union all
            select ID, 'A0003' as Header, A0003 as DATA
              from your_table_name
             where A0003 <> 0
            )t_1
            ORDER BY ID, DATA
    ) t_2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM