请考虑以下示例:
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选择第二列,但我没有成功。有人可以帮助我吗?
答案 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