Oracle SQL Pivot从同一表查询附加列

时间:2019-01-09 16:55:12

标签: sql oracle pivot

由于我是PIVOT函数的新手,因此很难进行以下查询:

样本数据:

Name  |  Tab | Attribute | Value
====================================
Set1  |  A   |  Street   | Wall St.
Set1  |  A   |  ZIP      | 12345
Set1  |  B   |  Street   | Route 66
Set1  |  B   |  No       | 7
Set1  |  C   |  Street   | (null)
Set2  |  A   |  Street   | Oxford St
Set2  |  A   |  ZIP      | (null)
Set2  |  B   |  No       | (null)

预期结果:

Name  | Street_from_Tab_A  |  ZIP  | No
=========================================
Set1  | Wall St.           | 12345 | 7
Set2  | Oxford St          | (null)| (null)

到目前为止我尝试过的事情:

select name, street_from_tab_a, zip, no from my_table
PIVOT (max(value) for attribute in ('Street' as street_from_tab_a, 'ZIP' as ZIP, 'No' as No)) 
where tab = 'A';

如何从选项卡“ B”中添加“否”作为列?

1 个答案:

答案 0 :(得分:3)

您似乎需要将Tab和Attribute结合使用:

SELECT name, street_from_tab_a, zip, no
  FROM My_Table
 PIVOT (max(value)
   FOR (tab, attribute) in (('A','Street') street_from_tab_a
                           ,('A','ZIP') zip
                           ,('B','No') no)) pvt