如果in失败,t-sql返回一个值

时间:2013-03-17 23:50:37

标签: sql-server tsql

我使用的是T-sql。我的SQL需要一些帮助。我正在使用IN语句,作为一个例子,我寻找1,32,21现在一些记录只有两个数字,我可以返回,' YES'如果它在列表中并且没有' NO'如果不是,那么改为计算数字,如果'是'。

UPDATE !!

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

该金额按每种类型的YES: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

1 个答案:

答案 0 :(得分:0)

如果我正确地读你,你的选择列表中可能会出现类似CASE WHEN count(tuc.value) = 0 THEN 'YES' ELSE 'NO' END的内容

或者,在看到数据更新后。我想这会做到这一点:

步骤1使用tu和tuc表之间的外连接。请参阅@ marc_s的评论 第2步是删除输出中的“id”列,或允许它为null。似乎如果用户没有给定的证书,则tuc中将没有行,因此该列对所有行都没有意义。
第3步是添加列CASE WHEN tuc.value IS NULL THEN 'NO' ELSE 'YES' END AS 'HasOrNot'