SQL - 连接两个表并根据分类列中的值有条件地 select 行
SQL - Join two tables and conditionally select rows based on value from a categorical column
我有两个 table 与 inner 连接。我必须根据分类列中值的存在,有条件地 select 从右边 table 仅一行。
条件: 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 |
预期:
| 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
如果应用于您问题中的示例数据 - 输出为
我有两个 table 与 inner 连接。我必须根据分类列中值的存在,有条件地 select 从右边 table 仅一行。
条件: 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 |
预期:
| 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
如果应用于您问题中的示例数据 - 输出为