Case

從多個 CASE 匹配中返回多行?

  • July 26, 2013

我想在我的查詢中添加一列,它將指定一行匹配的一個或多個類別。我想接受這個:

   +--------------+---------------+
Row | Product      | Quantity_Sold |
   +--------------+---------------+
1   | Coca-Cola    | 15            |
2   | Cigarettes   | 4             |
3   | Pretzel      | 6             |
4   | Beer         | 25            |
5   | Popcorn      | 10            |
6   | Candy Bar    | 10            |
   +--------------+---------------+

並返回:

   +--------------+---------------+----------------------+
Row | Product      | Quantity_Sold | Category             |
   +--------------+---------------+----------------------+
1   | Coca-Cola    | 15            | Beverages            |
2   | Cigarettes   | 4             | Controlled Substance |
3   | Pretzel      | 6             | Snacks               |
4   | Beer         | 25            | Beverages            |
5   | Beer         | 25            | Controlled Substance |
6   | Popcorn      | 10            | Snacks               |
7   | Candy Bar    | 10            | Snacks               |
   +--------------+---------------+----------------------+

請注意輸出的第 4-5 行,“Beer”位於兩行,因為它屬於兩個類別。

如果我嘗試使用 CASE 執行此操作,則只會計算第一個匹配項。

這個查詢

SELECT
   Product,
   Quantity_Sold,
   CASE
       WHEN
           Product IN ('Coca-Cola', 'Beer')
       THEN
           'Beverages'
   CASE
       WHEN
           Product IN ('Pretzel', 'Popcorn', 'Candy Bar')
       THEN
           'Snacks'
   CASE
       WHEN
           Product IN ('Cigarettes', 'Beer')
       THEN
           'Controlled Substance'
   END
       AS Category
FROM sales_table;

只會返回這個輸出

   +--------------+---------------+----------------------+
Row | Product      | Quantity_Sold | Category             |
   +--------------+---------------+----------------------+
1   | Coca-Cola    | 15            | Beverages            |
2   | Cigarettes   | 4             | Controlled Substance |
3   | Pretzel      | 6             | Snacks               |
4   | Beer         | 25            | Beverages            |
5   | Popcorn      | 10            | Snacks               |
6   | Candy Bar    | 10            | Snacks               |
   +--------------+---------------+----------------------+

(注意“啤酒”只出現一次)

那麼我怎樣才能讓它在它匹配的所有類別的單獨行上顯示呢?

加入將是這裡的最佳解決方案。

創建一個表,其中包含類別列表以及哪些產品與它們相關聯,例如 Product、Category,我們將其稱為 ProductCategories。然後加入這張桌子。

SELECT p.Product, p.Quantity_Sold, pc.Category
FROM sales_table p
JOIN ProductCategories pc ON pc.Product = p.Product'

這有一個額外的好處,即當您添加更多類別時不必修改您的案例語句(這很快變得難以/不可能維護),並且只需要簡單地插入新表。

引用自:https://dba.stackexchange.com/questions/47012