SQL不重复查找数据及把一列多行内容拼成一行
程序员文章站
2022-04-23 19:13:35
如下表: 表名:Test 1,查找表中字段重复的只查找一次 select distinct Col1 from Test ; select Col1 from Test where ID in(select min(ID) from Test group by Col1 ); 结果为: A B C ......
如下表:
表名:Test
ID | RowID | Col1 | Col2 |
1 | 1 | A | A |
2 | 1 | B | A |
3 | 1 | A | B |
4 | 1 | C | B |
1,查找表中字段重复的只查找一次
select distinct Col1 from Test ;
select Col1 from Test where ID in(select min(ID) from Test group by Col1 );
结果为:
A
B
C
2,统计并查询该字段出现的数量
SELECT Col1,COUNT(Col1) FROM Test GROUP BY Col1;
结果为:
A 2
B 1
C 1
3,把一列多行内容拼成一行
select STUFF ((select ','+F.Col1 from Test F where F.RowID= 1 order by F.ID FOR XML PATH('')),1,1,'') As Col3;
结果为:
Col3
A,B,A,C