【问题标题】:Pivot data from two tables从两个表中透视数据
【发布时间】:2019-04-05 18:51:33
【问题描述】:

我有两个表,Table_A 是一个工作流跟踪器,如下所示:

Table_A

Unique_ID    Status    Decision
1234         Open      Accept 
5678         Closed    Reject
9112         Closed    Accept
3141         Open      Reject

Table_B 包含上面的一些唯一 ID,以及已生成的各种警告消息(最多 4 条)。

Table_B

Unique_ID    Warning_Code    Warning
1234         1               Description1
1234         2               Description2
3141         1               Description2
5678         1               Description3
5678         2               Description1
5678         3               Description3

我希望能够对 Table_B 中的数据进行透视,以在行中显示 Table_A 中的所有唯一 ID,并让列显示该 ID 出现错误的次数,重要的是,错误是什么。预期结果是:

Unique_ID    Status    Decision    Warning_1     Warning_2     Warning_3      Warning_4
1234         Open      Accept      Description1  Description2      -              -
5678         Closed    Reject      Description3  Description1  Description3  Description4
9112         Closed    Accept           -             -            -              -    
3141         Open      Reject      Description3       -            -              -

我不确定这种枢轴是否甚至可以使用 SQL,因此感谢任何帮助。

【问题讨论】:

    标签: sql oracle pivot


    【解决方案1】:

    case when expression使用条件聚合

    select 
      a.Unique_ID,Status,Decision,
      max(case when Warning_Code=1 then Warning end) as Warning_1,
      max(case when Warning_Code=2 then Warning end) as Warning_2,
      max(case when Warning_Code=3 then Warning end) as Warning_3,
      max(case when Warning_Code=4 then Warning end) as Warning_4
    from tableA a inner join tableB b on a.Unique_ID=b.Unique_ID
    group by a.Unique_ID,Status,Decision
    

    【讨论】:

      【解决方案2】:

      聚合时的用例

      select Unique_ID,Status ,Decision,
      max(case when Warning_Code=1 then Warning end) as waring1
      max(case when Warning_Code=2 then Warning end) waring2,
      max(case when Warning_Code=3 then Warning end) waring3
      from tablea a join tableb b on a.Unique_ID=b.Unique_ID 
      group by Unique_ID,Status ,Decision
      

      【讨论】:

      • 恭喜获得 SQL 徽章。
      【解决方案3】:

      这是基本的pivot查询,你只需要进行左连接,以防A中的任何行在B中没有决定:

      select *
        from a left join b using (unique_id)
        pivot (max(warning) for warning_code in (1 w1, 2 w2, 3 w3, 4 w4))
      

      demo

      【讨论】:

        猜你喜欢
        • 2015-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-26
        • 2018-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多