[英]group distinct value on column two based on 1st column in sql server
Please consider the below example : 请考虑以下示例:
id name
1234 maria
1235 tamas
1236 helia
1234 maria
1235 jack
1235 david
What I want to do is to group the distinct value on the second column based on id : 我想做的是基于id将第二列上的不同值分组:
id name id name id name
1234 maria 1235 tamas 1236 helia
1235 jack
1235 david
I am not sure, but I think I should use cursor on id and then select the second column by that id but I wasn't successful. 我不确定,但是我想我应该在id上使用游标,然后通过该id选择第二列,但是我没有成功。 Can somebody help me out in this? 有人可以帮我吗?
Try this: 尝试这个:
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
Distinct
keyword should solve the purpose: 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
this would give them in separate table, but @Deepshika solution is fine also. 这会将它们放在单独的表中,但是@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.