2013-03-17 74 views
0

我正在使用T-sql。我需要一些關於我的SQL的幫助。我正在使用IN語句,作爲一個例子,我尋找1,32,21現在一些記錄將只有兩個數字在那裏我可以返回,'是'如果它是在列表中,'是' '如果它不是,那麼如果'是'就算數字。如果在失敗的地方t-sql返回一個值

更新!

id firstName uid value name      amount typeofthing 
161 sture  10470 1 Engineer Officer Class 1 1 certificate 
444 kumba  10472 1 Engineer Officer Class 1 3 certificate 

這是我的數據!正如你可以看到用戶UID 10470
只保存1個證書。我想才達到是有一個新行到我的數據是這樣

id firstName uid value name      amount typeofthing HasorNot 
161 sture  10470 1 Engineer Officer Class 1 1 certificate YES 
161 sture  10470 32 Engineer Officer Class 2 1 certificate NO 
161 sture  10470 21 Engineer Officer Class 3 1 certificate NO 

這量算的上是量:每種類型ES。 我希望得到他們沒有的課程/證書的名稱?我使用的SQL如下。由於

select 
    tuc.id, tu.firstName, tuc.uid, tuc.value, tc.name, 
    count(tuc.value) over (PARTITION BY tuc.uid) as 'amount', 'certificate' as 'typeofthing' 
from 
    t_user_certificates tuc, t_certificates tc, t_users tu 
where 
    tuc.[value] IN (1,32,21) 
    AND tuc.value = tc.id 
    AND tu.id = tuc.uid 

union 

select 
    tuc.id, tu.firstName, tuc.uid, tuc.value, tc.name, 
    count(tuc.value) over (PARTITION BY tuc.uid) as 'amount', 
    'courses' as 'typeofthing' 
from 
    t_user_courses tuc, t_courses tc, t_users tu 
where 
    tuc.[value] IN(2,16,21) 
    AND tuc.value = tc.id 
    AND tu.id = tuc.uid 
+0

這是不是很清楚你以後是什麼。您能否提供一些示例數據和預期結果? – 2013-03-18 02:33:55

+0

[踢壞的習慣:使用舊式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins。 aspx) - 使用ANSI - ** 92 ** SQL標準(** 20年前**!)廢止舊式*逗號分隔的表*樣式列表。 ***請停止使用它 – 2013-03-18 05:45:56

回答

0

如果我讀你的權利,好像你可能有一些像CASE WHEN count(tuc.value) = 0 THEN 'YES' ELSE 'NO' END在選擇列表

還是不行,看到數據更新之後。我認爲這樣做:

第1步是使用tu和tuc表之間的外連接。請參閱@ marc_s的評論。
第2步是擺脫輸出中的「id」列,或允許它爲空。看起來,如果用戶沒有給定的證書,tuc中將沒有行,所以這個列對所有行都沒有意義。
第3步是添加一列CASE WHEN tuc.value IS NULL THEN 'NO' ELSE 'YES' END AS 'HasOrNot'

+0

我應該如何把它放到我的SQL? – 2013-03-18 21:34:20

+0

編輯答案... – joelt 2013-03-19 00:18:02

相關問題