![](/img/trans.png)
[英]Select rows that has the same value in one column and different in other
[英]SQL - Select rows with same value in one column and choose the one with specific value in other column
刚开始学习SQL,遇到一个问题,自己解决不了。
我有下表:
ID | 项目 | 场地 |
---|---|---|
10301 | 一种 | field_10200 |
10302 | null | field_10201 |
10303 | 一种 | field_10202 |
10400 | null | field_10300 |
10401 | null | field_10301 |
10500 | null | field_10400 |
10502 | 乙 | field_10212 |
10505 | 一种 | field_10301 |
10506 | 乙 | field_10301 |
现在我只想 output 字段属于项目 A 或 null 但不是两者的 ID。
output 应如下所示:
ID | 项目 | 场地 |
---|---|---|
10301 | 一种 | field_10200 |
10302 | null | field_10201 |
10303 | 一种 | field_10202 |
10400 | null | field_10300 |
10500 | null | field_10400 |
10505 | 一种 | field_10301 |
这是解决方案:
select *
from Table t
where t.project = 'A'
or ( t.project is null
and not exists(select * from Table t2
where t2.project = 'A' and t2.field = t.field)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.