需要oracle查询将多行合并为一个,每行合并一列

时间:2019-08-20 17:39:49

标签: sql oracle pivot

我有以下数据集:

SELECT * FROM assets;    

AA_ASSET_ID ASSET_ID ASSET_NAME CLASS_ID CLASS_NAME
1023        1023     Head tip   4        Accessory
1023        1056     Sorter     2        Equipment
1023        1557     Workcell   1        Lab System

我想要一个查询,该查询可以将每个aa_asset_id输出到一行:

ID    Lab_System Equipment Accessory
1023  Workcell   Sorter    Head tip

我已经修补了PIVOT,但不能完全解决这个问题。有没有办法让它输出?

4 个答案:

答案 0 :(得分:2)

有条件聚合:

select
  aa_asset_id ID,
  max(case class_name when 'Lab System' then asset_name end) Lab_System,
  max(case class_name when 'Equipment' then asset_name end) Equipment,
  max(case class_name when 'Accessory' then asset_name end) Accessory
from assets
group by aa_asset_id

请参见demo
结果:

ID      LAB_SYSTEM  EQUIPMENT   ACCESSORY
1023    Workcell    Sorter      Head tip

答案 1 :(得分:1)

使用PIVOT运算符,您可以像这样进行操作:(请注意-WITH子句不是解决方案的一部分;我仅使用它是因为我没有实际的表。在对实际表进行测试时将其删除表格)

with
  assets (aa_asset_id, asset_id, asset_name, class_id, class_name) as (
    select 1023, 1023, 'Head tip', 4, 'Accessory'  from dual union all
    select 1023, 1056, 'Sorter'  , 2, 'Equipment'  from dual union all
    select 1023, 1557, 'Workcell', 1, 'Lab System' from dual
  )
select *
from   (select aa_asset_id, asset_name, class_name from assets)
pivot  (max(asset_name) for class_name in ('Lab System' as "Lab System",
                                           'Equipment'  as "Equipment" ,
                                           'Accessory'  as "Accessory" ))
;

AA_ASSET_ID Lab System Equipment Accessory
----------- ---------- --------  ---------
       1023 Workcell   Sorter    Head tip

答案 2 :(得分:1)

您可以使用PIVOT

SELECT *
FROM (
      SELECT aa_asset_id, asset_name, class_name
      FROM   assets
      )
PIVOT (
       MAX(asset_name) FOR (class_name) IN (
                                            'Lab System' as "Lab System", 
                                            'Equipment' as Equipment, 
                                            'Accessory' as Accessory )
      )

PIVOT XML,以便使用动态列名而不是对其进行硬编码。

也许像

SELECT *
FROM (
      SELECT aa_asset_id, asset_name, class_name
      FROM   assets
     )
PIVOT XML (
           MAX(asset_name) FOR (class_name) IN (SELECT DISTINCT class_name FROM assets)
          )

答案 3 :(得分:0)

您有机会使用MODEL子句:

select
  id, Lab_System, Equipment, Accessory
from assets
model
  return updated rows
  partition by (AA_ASSET_ID id)
  dimension by (CLASS_NAME)
  measures (
    asset_name,
    cast('' as varchar2(8)) Accessory,
    cast('' as varchar2(8)) Equipment,
    cast('' as varchar2(8)) LAB_SYSTEM
  ) rules (
    Accessory['PIVOT'] = asset_name['Accessory'],
    Equipment['PIVOT'] = asset_name['Equipment'],
    LAB_SYSTEM['PIVOT'] = asset_name['Lab System']
  );

输出:

|  ID  | LAB_SYSTEM | EQUIPMENT | ACCESSORY |
+------+------------+-----------+-----------+
| 1024 | Foo        | (null)    | Bar       |
| 1023 | Workcell   | Sorter    | Head tip  |

SQL Fiddle上演示。