在sql查询中将多行合并为一行?

时间:2015-08-14 06:42:48

标签: sql-server

在名为User Name | Gmail | Yahoo | Hotmail Sankar | X | NULL | NULL Aravinth | NULL | X | NULL Pavithran | NULL | NULL | X 的表格中,记录如下,

User Name   |  Gmail   |  Yahoo  | Hotmail
Sankar      |   X      |  X      |  X

我的例外结果是:

{{1}}

请帮我解决这个问题, 提前致谢

2 个答案:

答案 0 :(得分:0)

您需要在NULL

的帮助下检查每列是ISNULL吗?
declare @temp table 
(
name nvarchar(11),
gmail nvarchar(11),
yahoo nvarchar(11),
hotmail nvarchar(11))

insert into @temp values ('snkar'   ,'X' ,  NULL,  NULL)
insert into @temp values ('avinth' ,NULL, 'Y'  ,  NULL)
insert into @temp values ('vithran',NULL,NULL  ,'Z'  )

select * from @temp

select 
name,isnull(gmail,isnull(yahoo,hotmail)) gmail,
isnull(yahoo,isnull(gmail,hotmail)) yahoo,
isnull(hotmail,isnull(gmail,yahoo)) hotmail    
from @temp 

如果我们有多个具有相同名称的行,我们必须过滤相同的数据,这个方法会有所帮助

insert into @temp values ('snkar'   ,'X' ,  NULL,  NULL)
insert into @temp values ('snkar' ,NULL, 'X'  ,  NULL)
insert into @temp values ('snkar',NULL,NULL  ,'X'    )

select name,max(gmail) gmail,max(yahoo) yahoo,max(hotmail) hotmail
from @temp
group by name

答案 1 :(得分:0)

COALESCE更合适

DECLARE @temp TABLE
(
    name nvarchar(11),
    gmail nvarchar(11),
    yahoo nvarchar(11),
    hotmail nvarchar(11)
)

INSERT INTO @temp VALUES ('snkar'   ,'X' ,  NULL,  NULL)
INSERT INTO @temp VALUES ('avinth' ,NULL, 'Y'  ,  NULL)
INSERT INTO @temp VALUES ('vithran',NULL,NULL  ,'Z'  )

SELECT * 
FROM @temp

SELECT 
name, COALESCE(gmail,yahoo,hotmail) gmail,
COALESCE(yahoo,gmail,hotmail) yahoo,
COALESCE(hotmail,gmail,yahoo) hotmail    
FROM @temp