2012-11-29 99 views
3

我有一個表記錄課程進度的狀態。當課程開始時,每個用戶/課程共同添加一條新記錄。課程完成後,該記錄會更新爲「已完成」狀態。我需要爲從未完成任何課程的用戶找到記錄。單表查詢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 

任何幫助理解。

回答

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

+1相同的邏輯,我的答案。當我可以使用連接時,我有一種(可能是莫名其妙的)對IN的反感......優化器很可能以同樣的方式處理... – sebt

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 
) 
+2

+1對於某些RDBMS,您需要在總和'HAVING中使用'CASE' SUM(如果狀態='C'THEN 1 ELSE 0 END)= 0',如果RDBMS沒有爲布爾比較返回1(像MySQL那樣) –

+0

好點。謝謝。 –

+0

您可以選擇3列並按1分組嗎?我是MS風格的SQL程序員,我不能在我使用的SQL中! – sebt

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 
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)