行存在的情况

时间:2014-02-26 20:41:01

标签: sql sql-server

我有一个在tblKite上执行左连接的查询.id = tblColorKites = idKite

它返回:

id  kitename    color
1   Sword   blue
1   Sword   green
1   Sword   yellow



tblColor_Kites      
id  color   idKite
1   blue    1
2   green   1
3   yellow  1

我想要的是

id  isBlue  isGreen isYellow    isBrown
1   TRUE    TRUE    TRUE    FALSE

我可以通过执行这样的案例来做到这一点:

  case when (select id from tblKite left join tblColor_Kites on     
 tblKite.id=tblColorKites=idKite where tblKite.id='1' and tbl_color_kite.id='2') = 2 
 then   'True' else 'False' end as 'isGreen'

但是,我想知道是否有更有效的方式。

1 个答案:

答案 0 :(得分:0)

作为所有案例的替代方案,您可以使用Pivot,例如:

演示数据:

create table #tblKite (id smallint, kitename varchar(10),  color varchar(10)) 
insert into #tblKite values (1,'Sword','blue') 
insert into #tblKite values (1,'Sword','green') 
insert into #tblKite values (1,'Sword','yellow')

create table #tblColor_Kites (id smallint,  color varchar(10),   idKite smallint) 
insert into #tblColor_Kites values (1   ,'blue',1) 
insert into #tblColor_Kites values (2   ,'green',1) 
insert into #tblColor_Kites values (3   ,'yellow',1)

使用透视查询:

select id,IIF([blue] is not NULL,'True','False') as isBlue, 
IIF([red] is not null,'True','False') as isRed, 
IIF([yellow] is not null,'True','False') as isYellow, 
IIF([green] is not null,'True','False') as isGreen 
FROM
(select #tblKite.id,#tblKite.color,idKite 
    from #tblKite left join #tblColor_Kites ON  
    #tblKite.id = #tblColor_Kites.idKite) x 
     PIVOT (max(idKite) for color in ([blue],[red],[yellow],[Green])) p

这将为您提供预期的结果,主要是Pivot将数据转换为列,您需要定义函数以对结果进行分组,在您的情况下,对于每种颜色,最大值将返回idKite或idKite或Null。

http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

问候。