根据sql server中的第一列对第二列的不同值进行分组

时间:2014-11-28 06:42:22

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

请考虑以下示例:

id    name
1234   maria
1235   tamas
1236   helia
1234   maria
1235   jack
1235   david

我想要做的是根据id:

对第二列的不同值进行分组
id    name      id      name      id       name
1234  maria     1235    tamas     1236     helia
                1235    jack
                1235   david 

我不确定,但我认为我应该在id上使用游标然后按该ID选择第二列,但我没有成功。有人可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT A.id, MAX(STUFF(B.name, 1, 1, '')) AS name 
FROM tableA A 
CROSS APPLY(SELECT ',' + A1.name FROM tableA A1 WHERE A.id = A1.id FOR XML PATH('')) AS B (name)
GROUP BY A.id

答案 1 :(得分:0)

Distinct关键字应解决目的:

declare @test table ( id int, name varchar(20))

insert into @test values 
(1234,'maria'),
(1235,'tamas'),
(1236,'helia'),
(1234,'maria'),
(1235,'jack'),
(1235,'david')

select distinct id,name  from @test

答案 2 :(得分:0)

这会在单独的表中给出它们,但是@Deepshika解决方案也没问题。

DECLARE @ID INT
DECLARE @getID CURSOR
SET @getID = CURSOR FOR
select distinct id
from [work].[dbo].[FORM105]
order by id
OPEN @getID
FETCH NEXT
FROM @getID INTO @ID
WHILE @@FETCH_STATUS = 0 
BEGIN 
select distinct id,name
from [work].[dbo].[FORM105]
where id=@ID
FETCH NEXT
FROM @getID INTO @ID
END
CLOSE @getID
DEALLOCATE @getID