简体   繁体   中英

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

I have two tables with inner join. I have to conditionlly select only one row from right table based on the existence of a value in categorical column.

Condition : If blue exists, select blue else select green

Table-A:

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

Table-B:

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

Expected :

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

This should work for you:

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

Consider below approach

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                

if applied to sample data in your question - output is

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM