简体   繁体   English

SQL - 根据分类列的值连接两个表和有条件地 select 行

[英]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.我必须有条件地 select 根据分类列中值的存在,右表中只有一行。

Condition : If blue exists, select blue else select green条件:如果蓝色存在,select 蓝色,否则 select 绿色

Table-A:表-A:

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

Table-B:表-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如果应用于您问题中的示例数据 - output 是

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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