簡體   English   中英

返回列表中的第一個非NULL值;如果沒有非NULL值,則返回NULL

[英]Return the first non-NULL value in the list, or NULL if there are no non-NULL values

我希望能夠做到這一點,返回列表中的第一個非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;

我查詢的目的是確保客戶擁有主要商品,而不僅是已購買商品的標簽,而且商品中可能有一個標簽屬於多個商品,您將在下面看到喬恩和邁克如何匹配商品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匹配了,因此空值從結果集中消失了,但是由於Jay沒有匹配項,所以保留了Null值。

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

我懷疑使用聚合可以得到想要的結果:

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值。

編輯:

如果希望上述查詢為客戶消除空值,則可以將其調整為:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM