SQL查询帮助单表查询

时间:2012-11-29 17:40:02

标签: sql

我有一张表记录了课程进度的状态。在课程开始时为每个用户/课程组合添加新记录。课程结束后,该记录将以“已完成”状态更新。我需要为从未完成任何课程的用户找到记录。

示例表:

User  Course  Status
A      1       S
A      2       C
B      1       S
C      2       S
D      2       C
C      3       S

我需要一个查找以下内容的查询:

User  Course  Status
B      1        S
C      2        S
C      3        S

感谢任何帮助。

4 个答案:

答案 0 :(得分:2)

select user, course, status
from your_table
where user in 
(
    select user
    from your_table
    group by user
    having sum(CASE WHEN status = 'C' THEN 1 ELSE 0 END) = 0
)

答案 1 :(得分:1)

Select User, Course, Status from MyTable where User not in (Select Distinct User from MyTable where Status = 'C')

答案 2 :(得分:1)

SELECT User,Course,Status FROM YourTable a
LEFT JOIN
(SELECT DISTINCT User FROM YourTable WHERE Status='C') CompletedAnything
ON a.User=CompletedAnything.User
WHERE COmpletedAnything.User IS NULL

答案 3 :(得分:0)

这是一个SQL小提琴,可以为您提供所需内容: http://sqlfiddle.com/#!2/b6988/1

查询是这样的:

select User, Course, Status
from mytable
where User not in 
  (select distinct User from mytable where status = 'C' ans User is not null)