重写oracle sql查询

时间:2014-07-10 13:25:06

标签: sql oracle11g

我当前的查询是

SELECT
STATUS, 
POSTAL_CODE, 
CITY_STATE,
    (case when SERVICE = 1 THEN org_id) end) AS WATER,
    (case when SERVICE = 2 THEN org_id) end) AS COFFEE,
    (case when SERVICE = 3 THEN org_id) end) AS FILTRATION
FROM MAP
WHERE POSTAL_CODE = 02216

结果:

Status      Zip     City_State  Water  Coffee  Filtration

Serviceable 02216   BOSTON,MA.  BEL    null   null
Serviceable 02216   BOSTON,MA.  null   BDG    null
Serviceable 02216   BOSTON,MA.  null   null   BEL

我想将此结果折叠成一行。是否有一些我可以使用的优雅选择,或者我应该使用像XMLAGG,XMLELEMENT这样的函数来将结果折叠成一行?还有,有更好的方法来编写这些案例陈述吗?可能使用where子句?

尝试了a_horse_with_no_name的建议如下:

SELECT  STATUS, 
        POSTAL_CODE,
        SERVICE_ITEM_ID,
        MAX((case when SERVICE = 1 THEN org_id)) AS WATER,
        MAX((case when SERVICE = 2 THEN org_id)) AS COFFEE,
        MAX((case when SERVICE = 3 THEN org_id)) AS FILTRATION
FROM MAP
WHERE POSTAL_CODE = '02216'
GROUP BY STATUS, POSTAL_CODE, SERVICE_ITEM_ID;

STATUS  POSTAL_CODE SERVICE_ITEM_ID WATER   COFFEE  FILTRATION
Serviceable 02216   1300            BEL     null        null
Serviceable 02216   1302            null    BDG         null
Serviceable 02216   1304            null    null        BEL

结果仍然相同。

2 个答案:

答案 0 :(得分:2)

使用group by和聚合函数:

SELECT STATUS, 
       POSTAL_CODE, 
       CITY_STATE,
       max(case when SERVICE = 1 THEN org_id end) AS WATER,
       max(case when SERVICE = 2 THEN org_id end) AS COFFEE,
       max(case when SERVICE = 3 THEN org_id end) AS FILTRATION
FROM MAP
WHERE POSTAL_CODE = '02216'
GROUP BY status, postal_code, city_state

由于聚合忽略NULL值,因此会减少为一行。


我认为postal_codevarchar列,因此您还应将其与字符串/ varchar值进行比较。 02216是一个数字(2216),而'02216'是一个字符串。

答案 1 :(得分:0)

尝试使用PIVOT(我认为它仅适用于Oracle 11g以及之后)。此外,我是他们的新手,但我99%肯定你将如何在一行中获得你想要的一切。

SELECT * FROM ( SELECT STATUS, POSTAL_CODE, CITY_STATE, (max(case when SERVICE = 1 THEN org_id end) AS WATER || max(case when SERVICE = 2 THEN org_id end) AS COFFEE || max(case when SERVICE = 3 THEN org_id end) AS FILTRATION) AS S1 FROM MAP WHERE POSTAL_CODE = '02216' GROUP BY status, postal_code, city_state ) PIVOT ( S1 FOR S1 IN ('WATER', 'COFFEE', 'FILTRATION') )