如何在Oracle

时间:2015-12-15 06:19:45

标签: sql oracle oracle11g transpose

这是我的表

Equipmentid    Application   Value
===========    ===========   =====
k001              THK         True
k001              BHK         False
k001              KHK         True

这是我的预期:

Equipmentid    THK   BHK    KHK
===========    ===   ===    ===
k001           True  False  True

我正在尝试使用普通的转置Oracle使用max decode但最后需要提到AS [tablename],我想在行名称上动态创建行到列,这个数据库将涉及很多应用程序。谢谢你们

3 个答案:

答案 0 :(得分:2)

您好尝试使用PIVOT,

WITH x(equipment_id, application, VALUE ) 
     AS (SELECT 'k001', 'THK', 'TRUE' FROM DUAL UNION ALL
         SELECT 'k001', 'BHK', 'FALSE' FROM DUAL UNION ALL
         SELECT 'k001', 'KHK', 'TRUE' FROM DUAL  UNION ALL
         SELECT 'k002', 'KHK', 'FALSE' FROM DUAL UNION ALL
         SELECT 'k002', 'THK', 'FALSE' FROM DUAL UNION ALL
         SELECT 'k002', 'BHK', 'FALSE' FROM DUAL )

  SELECT * FROM
(
  SELECT equipment_id, value, application
  FROM x
)
PIVOT
(
  MAX(value)
  FOR application IN ('THK', 'BHK', 'KHK')
) order by equipment_id;

或者,如果你想拥有动态列,你可以在IN子句中使用子查询,然后使用PIVOT XML,但结果将是XML TYPE,我不知道如何提取值。(只是说)如果你想了解有关如何使用pl / sql动态执行此操作的更多信息。 Read hereHere's the source

  SELECT * FROM
(
  SELECT equipment_id, value, application
  FROM x
)
PIVOT XML
(
  MAX(value)
  FOR application IN (SELECT DISTINCT application from x)
) order by equipment_id;

答案 1 :(得分:1)

试试这个。

SELECT EQUIPMENTID,
max(case  when  APPLICATION = 'THK' then VALUE end) as "THK",
max(case  when  APPLICATION = 'BHK' then VALUE end) as "BHK",
max(case  when  APPLICATION = 'KHK' then VALUE end) as "KHK"
FROM [tablename]
group by EQUIPMENTID;

答案 2 :(得分:0)

在这种情况下你可以left join

SELECT t1.Equipmentid, t2.Value AS 'THK', t3.Value AS 'BHK', t4.Value AS 'KHK' FROM TABLE t1
     LEFT JOIN (SELECT Equipmentid, Value FROM TABLE WHERE Application = 'THK') AS t2 ON (t1.Equipmentid = t2.Equipmentid)
     LEFT JOIN (SELECT Equipmentid, Value FROM TABLE WHERE Application = 'BHK') AS t3 ON (t1.Equipmentid = t3.Equipmentid)
     LEFT JOIN (SELECT Equipmentid, Value FROM TABLE WHERE Application = 'KHK') AS t4 ON (t1.Equipmentid = t4.Equipmentid)

即使它可以解决。但是这种方法在我看来并不好。希望它能帮助你