簡體   English   中英

SQL - 根據分類列的值連接兩個表和有條件地 select 行

[英]SQL - Join two tables and conditionally select rows based on value from a categorical column

我有兩個帶內部連接的表。 我必須有條件地 select 根據分類列中值的存在,右表中只有一行。

條件:如果藍色存在,select 藍色,否則 select 綠色

表-A:

| ID | Name  |
| ---| ------|
| 01 | row   |
| 02 | row   |
| 03 | row   |

表-B:

| ID | CatCol  |
| ---| --------|
| 01 | blue    |
| 01 | green   |
| 01 | red     |
| 02 | green   |
| 02 | red     |
| 03 | blue    |

預期

| ID | CatCol  |
| ---| --------|
| 01 | blue    |
| 02 | green   |
| 03 | blue    |

這應該適合你:

SELECT b.ID, MIN(b.CatCol) as CatCol 
FROM table_b b
INNER JOIN table_a a ON 
b.id = a.id
GROUP BY b.ID

考慮以下方法

select a.ID, string_agg(CatCol, '' order by if(CatCol = 'blue', 1, 2) limit 1) CatCol
from table_a a left join table_b b
on a.ID = b.ID and CatCol in ('blue', 'green')
group by ID                

如果應用於您問題中的示例數據 - output 是

在此處輸入圖像描述

暫無
暫無

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

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