我想获得特定用户名
的唯一行值为yes如果两个行对于该特定用户名都为yes,或者两者都没有,则它不应出现在输出中。
下面是示例示例和输出。如何使用sql查询完成?
+----------+-----+-------+
| username | id | col2 |
+----------+-----+-------+
| a | 1 | yes |
| a | 2 | yes |
| b | 3 | yes |
| b | 4 | no |
| c | 5 | no |
| c | 6 | no |
+----------+----+--------+
输出
+---------+---+------+
| username|id | col2 |
+---------+---+------+
| b |3 | yes |
+---------+---+------+
非常感谢任何帮助
答案 0 :(得分:2)
对于本练习,您不需要连接或子查询;所有你需要的是GROUP BY和HAVING。
select username, 'yes' as col2
from table_name
group by username
having min(col2) != max(col2)
修改(以解决OP的重述问题):
select username, min(id) keep (dense_rank last order by col2) as id, 'yes' as col2
from table_name [.... the rest as above]
答案 1 :(得分:0)
如果每个用户名的行只有两个
select t1.username , t1.col2
from mytable t1
inner mytable t2 on t1.username = t2.username
and t1.col2 = 'yes' and t2.col2 ='no'
答案 2 :(得分:0)
据推测,每个用户名可以有两行以上,这样就会找到只有一个用户名的用户名。
SELECT username, MIN(id), col2
FROM YourTable
WHERE col2 = 'yes'
GROUP BY username, col2
HAVING COUNT(*) = 1