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