返回列表中的第一个非NULL值,如果没有非NULL值,则返回NULL

时间:2014-12-03 14:24:58

标签: sql oracle

我希望能够这样做,返回列表中的第一个非NULL值,如果没有非NULL值,则返回NULL。我正在对Oracle数据库使用Oracle SQL。

SELECT
    a.customer,
    a.item,
    b.item,
FROM
    Orders a
        LEFT JOIN
        item_desc c
        ON
    a.item= c.tag1 OR
    a.item= c.tag2 OR
    a.item= c.tag3 OR
    a.item= c.tag4 OR
    a.item= c.tag5
        LEFT JOIN
        Orders b
        ON
        c.item = b.item AND
    a.customer = b.customer
WHERE
    a.itemLIKE 'CP%'
GROUP BY
    a.customer,
    a.item,
    b.item;

我的查询的目的是确保客户拥有主要商品而不仅仅是购买商品的标签,但是项目中可能有一个标签属于多个商品,您将在下面看到Jon和Mike如何匹配对于项目X和Null值,因为您看到项目422是项目X和B的标记。 结果如下所示:

Customer    Item    Item
Jon         422     X
Jon         424     NULL
Mike        424     X
Mike        422     Null
Jay         422     Null
Dan         422     B
Dan         422     Null

我的查询的目的是确保客户在购买的商品上有所需的标签,但项目中可能有一个属于多个商品的标签。

我希望结果如下:由于Jon和Mike有匹配,因此null值从结果集中消失,但由于Jay没有匹配,所以Null值保持不变。

Customer    Item    Item
Jon         422     X
Mike        424     X
Jay         422     Null
Dan         422     B

1 个答案:

答案 0 :(得分:1)

我怀疑你可以使用聚合获得你想要的东西:

SELECT a.customer, a.item, max(b.item)
FROM Orders a LEFT JOIN
     item_desc c
     ON a.item in (c.tag1, c.tag2, c.tag3, c.tag4, c.tag5) LEFT JOIN
     Orders b
     ON c.item = b.item AND
        a.customer = b.customer
WHEREa.item LIKE 'CP%'
GROUP BY a.customer, a.item;

如果有NULL值,则返回非NULL值。

编辑:

如果您希望上述查询消除客户的空值,则可以将其调整为:

SELECT customer, item, bitem
FROM (SELECT a.customer, a.item, max(b.item) as bitem,
             row_number() over (partition by a.customer order by (case when a.item is not null then 1 else 2 end) ) as seqnum
      FROM Orders a LEFT JOIN
           item_desc c
           ON a.item in (c.tag1, c.tag2, c.tag3, c.tag4, c.tag5) LEFT JOIN
           Orders b
           ON c.item = b.item AND
              a.customer = b.customer
      WHERE a.item LIKE 'CP%'
      GROUP BY a.customer, a.item
     ) t
WHERE bitem is not null or seqnum = 1;
相关问题