在Oracle / SQL中,如何选择具有相同列id但非id列的值不同的行

时间:2013-07-02 07:12:38

标签: sql oracle

在下表中,我想展示 is_logged_in 标志中显示为0和1的每个 user_id

__________________________
| user_id | is_logged_in |
+------------------------+
|    A    |      1       |
+------------------------+
|    B    |      1       |
+------------------------+
|    B    |      0       |
+------------------------+
|    C    |      0       |
+------------------------+
|    D    |      0       |
+------------------------+
|    D    |      1       |
+------------------------+
|    C    |      0       |
+------------------------+

可以在没有GROUP BY条件的情况下完成吗?如果可能,您还可以告诉我如何在没有GROUP BY的情况下进行查询。谢谢你。

查询后的结果:

___________
| user_id |
+---------+
|    B    |
+---------+
|    D    |
+---------+

3 个答案:

答案 0 :(得分:2)

您尝试实施的逻辑是什么?为什么要返回B和D而不是A或C?

如果问题是“向我展示user_id旗帜中出现0和1的每个is_logged_in

select user_id
  from table_name
 group by user_id
having count( distinct is_logged_in ) = 2

select user_id
  from table_name
 where is_logged_in = 0
intersect
select user_id
  from table_name
 where is_logged_in = 1

select a.user_id
  from table_name a,
       table_name b
 where a.rowid != b.rowid
   and a.user_id = b.user_id
   and a.is_logged_in = 0
   and b.is_logged_in = 1

答案 1 :(得分:0)

SELECT *
FROM table
WHERE (user_id = 'B' or user_id = 'D')

答案 2 :(得分:0)

select distinct user_id
from table_name a 
inner join table_name b on a.user_id = b user_id
where a.is_logged_in <> b.is_logged_in