简体   繁体   English

基于SQL Server中的第一列在第二列上分组不同的值

[英]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.

相关问题 基于 SQL 服务器中 select 查询中第一列值的值格式 - Value format based on 1st Column value in select query in SQL server 基于第一列的组计数 - Counting based on group of 1st column SQL Server:从同一列中具有匹配值的第一行之后的列中选择所有行 - SQL Server : select all rows from a column after the 1st row with matching value from the same column SQL Server:联接两行。 第一列的所有列和第二列的第一列使用别名 - SQL Server : Join two rows. All columns from the 1st and 1 column from the second using an alias 如何连接两个SQL表,将第二个表中的值放入第一个表中的列? - How can I join two SQL tables, putting a value from the 2nd table into a column in the 1st? 如何从SQL Server中的列中删除第一个字符 - How to remove the 1st character from a column in SQL Server SQL ORDER BY 第一列,但如果第一列为空,则用第二列中的值替换空值 - SQL ORDER BY 1st column, but if 1st column is empty replace the empty value by a value from 2nd column SQL Server - 选择两列的不同,其中所选的不同列具有基于另外两列的最大值 - SQL Server - Select Distinct of two columns, where the distinct column selected has a maximum value based on two other columns 需要根据 T-SQL 中的“入学日期”列计算出的第一个“3 个月”为列中的每个值添加 3 个月 - Need to add 3 months to each value within a column, based on the 1st '3 Months' calculated off the Admission Date column in T-SQL 按两次返回第一列值进行分组 - Group By returning 1st column values twice
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM