在sql server 2008分组时获取相关的字符串数据

时间:2016-04-07 14:35:24

标签: sql sql-server sql-server-2008

我有一张表:

id   name1   name2   name3
1    yok     null     null
1    null    yok      null
1    null    null     yok

我想要的输出是:

id   name1   name2   name3
1    yok     yok     yok

我尝试的是:

select id, name1, name2, name3
from trial
group by id

表创建脚本如下:

Create table trial (id int, name1 varchar(10),name2 varchar(10),name3 varchar(10))
insert into trial values (1,'yok',null,null)
insert into trial values (1,null,'yok',null)
insert into trial values (1,null,null,'yok')

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以尝试下面的语句

Select 
  id,
  max(name1) name1,
  max(name2) name2,
  max(name3) name3
from trial
group by id

<强> Sql demo