Oracle - 将行转换为列

时间:2018-02-06 17:27:54

标签: sql oracle

我的表格包含属性id_customer,product,id_department。

产品价值 - 手机,导航,笔记本

    id_customer    product       id_department 
    1              mobile        5
    1              navigation    5
    1              mobile        6
    2              notebook      5
    3              notebook      6

我想将其转换为:

    id_customer          id_department   mobile   navigation    notebook
    1                    5               true     true          (null)
    1                    6               true     (null)        (null)
    2                    5               (null)   (null)        true
    3                    6               (null)   (null)        true

是否可以使用Oracle SQL执行此操作?

1 个答案:

答案 0 :(得分:2)

使用pivot运算符(需要Oracle 11.1或更高版本):

with
  inputs ( id_customer, product, id_department ) as ( 
    select 1, 'mobile'    , 5 from dual union all
    select 1, 'navigation', 5 from dual union all
    select 1, 'mobile'    , 6 from dual union all
    select 2, 'notebook'  , 5 from dual union all
    select 3, 'notebook'  , 6 from dual
  )
-- End of simulated data (not part of the solution).
-- SQL query begins below this line. Use your actual table and column names.
select id_customer, id_department, mobile, navigation, notebook
from   inputs
pivot (max('true') for product in ('mobile' as mobile, 'navigation' as navigation,
                                   'notebook' as notebook))
order by id_customer, id_department
;

ID_CUSTOMER ID_DEPARTMENT MOBILE     NAVIGATION NOTEBOOK
----------- ------------- ---------- ---------- ----------
          1             5 true       true     
          1             6 true          
          2             5                       true
          3             6                       true

唯一的"技巧"这是要转动的数量。它必须始终是一个聚合函数 - 我使用max()。由于你想要的只是一个'true'标记,我正在转动一个常量字符串的max,即字符串'true'