在查询中使用解码多个结果?

时间:2012-10-30 17:35:49

标签: sql oracle group-by left-join decode

SELECT PE.PHYS_RESR_ID,PE.EQMT_INIT,  PE.EQMT_NBR,
decode (EEU.dimn_type , 'EXTHGT', EEU.dimn_valu) as EXTHGT, 
decode(EEU.dimn_type, 'EXTHGT', EEU.uom_code) as UNIT_EXTHGT,
decode (EEU.dimn_type , 'INHGT', EEU.dimn_valu) as INHGT, 
decode(EEU.dimn_type, 'INHGT', EEU.uom_code) as UNIT_INHGT,
decode (EEU.dimn_type , 'INWDTH', EEU.dimn_valu) as INWDTH, 
decode(EEU.dimn_type, 'INWDTH', EEU.uom_code) as UNIT_INWDTH

FROM EQU_EQMT PE
  left join EQU_EQMT_DIMN EEU 
  on  EEU.PHYS_RESR_ID = PE.PHYS_RESR_ID      
and   ( EEU.POS_DESC is null or EEU.POS_DESC ='VALU' or EEU.POS_DESC ='valu');

但是当我跑的时候。查询为我返回的每个解码返回一行。我想要一个这个id pe.phys_resr_id的行与同一行中的不同数据。有什么建议? 我希望它能像这样给我:

+-------------+-------------+---------+--------+------------+---------+------------+------------+---------------+
| PHYS_RESR_ID| EQMT_INIT   | EQMT_NBR| EXTWD  | UNIT_EXTWD | INHGT   | UNIT_INGHT | INWDTH      | UNIT_INWDTH  | 
+-------------+-------------+---------+--------+------------+---------+------------+-------------+--------------+
|  456        | AC          | 3       |   4    |   IN       | NULL    | NULL       | NULL        | NULL     | 
|  324        | AD          | 45      |   67   |   IN       | 56      | IN         | NULL        | NULL     |
|  132        | B           | 65      |  54    |   IN       | 78      | IN         | 34          |  IN      |    
+----+-------------+---------+--------+--------+------------+---------+------------+-------------+--------------+

1 个答案:

答案 0 :(得分:1)

我会将MAX(DECODE(...))成语用于pivot

SQL> SET NULL [NULL]
SQL> SELECT   pe.phys_resr_id
  2  ,        pe.eqmt_init
  3  ,        pe.eqmt_nbr
  4  ,        MAX(DECODE(eeu.dimn_type, 'EXTHGT', eeu.dimn_valu)) AS exthgt
  5  ,        MAX(DECODE(eeu.dimn_type, 'EXTHGT', eeu.uom_code))  AS unit_exthgt
  6  ,        MAX(DECODE(eeu.dimn_type, 'INHGT' , eeu.dimn_valu)) AS inhgt
  7  ,        MAX(DECODE(eeu.dimn_type, 'INHGT' , eeu.uom_code))  AS unit_inhgt
  8  ,        MAX(DECODE(eeu.dimn_type, 'INWDTH', eeu.dimn_valu)) AS inwdth
  9  ,        MAX(DECODE(eeu.dimn_type, 'INWDTH', eeu.uom_code))  AS unit_inwdth
 10  FROM     equ_eqmt  pe
 11           LEFT JOIN equ_eqmt_dimn eeu ON eeu.phys_resr_id = pe.phys_resr_id
 12  AND      (eeu.pos_desc IS NULL OR eeu.pos_desc = 'VALU' OR eeu.pos_desc ='valu')
 13  GROUP BY pe.phys_resr_id
 14  ,        pe.eqmt_init
 15  ,        pe.eqmt_nbr
 16  ;

PHYS_RESR_ID EQMT_INIT    EQMT_NBR     EXTHGT UNIT_EXTHG      INHGT UNIT_INHGT     INWDTH UNIT_INWDT
------------ ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
         456 AC                  3          4 IN         [NULL]     [NULL]     [NULL]     [NULL]
         324 AD                 45         67 IN                 56 IN         [NULL]     [NULL]
         132 B                  65         54 IN                 78 IN                 34 IN

SQL>