如果“WRONG”列永远不会显示“YES”,我想从表中选择一行(多次出现)。这意味着该行存在100次而只有一次 WRONG = yes,然后不在结果中显示任何行。
*如果可能的话,没有变量和while循环请。如果无法完成,请继续并使用变量发布解决方案。
以下是表结构的示例:
表1
USER--WRONG--otherColumns
bob data
bob data
bob data
bob data
bob data
bob YES data
bob data
bob data
jon data
结果应该是: jon(因为有一次错误等于用户bob的是)
此代码不会省略所有bob。只省略一个:
SELECT USER FROM table1 WHERE wrong <> 'yes'
答案 0 :(得分:2)
select user
from table1 a
where not exists (select 1 from table1 b where a.user = b.user and wrong = 'yes')
答案 1 :(得分:1)
SELECT
USER
FROM
Mytable T1
WHERE
NOT EXISTS (SELECT 3
FROM Mytable T2
WHERE T1.user = T2.User AND T2.Wrong = 'YES')
你也可以使用EXCEPT(标签说tsql),这给出了相同的计划
SELECT
USER
FROM
Mytable
EXCEPT
SELECT
USER
FROM
Mytable
WHERE
Wrong = 'YES'
对于EXISTS的仇敌。假设USER列没有NULL,否则失败
SELECT
USER
FROM
Mytable T1
WHERE
T1.USER NOT IN (SELECT T2.USER
FROM Mytable T2
WHERE T2.Wrong = 'YES')
答案 2 :(得分:1)
SELECT *
FROM table1 t1
WHERE NOT EXISTS
(SELECT 1
FROM table1 t2
WHERE t1.user = t2.user
AND wrong = 'yes');
答案 3 :(得分:0)
select user from table1 where wrong <> 'yes' group by user