sq如何实现多字段分组

tomzjt123 2011-11-10 07:24:52
比如我有以下分组
a b
1 2
2 3
4 5


我想把a b 两组内容不重复的列出来

得到 1 2 3 4 5

应该怎么写sql语句?
...全文
111 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
q465897859 2011-11-10
  • 打赏
  • 举报
回复
Create table #T([a] int,[b] int)
Insert #T
select 1,2 union all
select 2,3 union all
select 4,5
Go
select name=stuff((select distinct ' '+ltrim(a) from (select a from #t
union all
select B from #T)a for xml path('')),1,1,'')
geniuswjt 2011-11-10
  • 打赏
  • 举报
回复
哦,再行转列下[Quote=引用 4 楼 geniuswjt 的回复:]

SQL code

select a from tb
union
select b from tb

引用楼主 tomzjt123 的回复:
比如我有以下分组
a b
1 2
2 3
4 5


我想把a b 两组内容不重复的列出来

得到 1 2 3 4 5

应该怎么写sql语句?
[/Quote]
geniuswjt 2011-11-10
  • 打赏
  • 举报
回复

select a from tb
union
select b from tb
[Quote=引用楼主 tomzjt123 的回复:]
比如我有以下分组
a b
1 2
2 3
4 5


我想把a b 两组内容不重复的列出来

得到 1 2 3 4 5

应该怎么写sql语句?
[/Quote]
--小F-- 2011-11-10
  • 打赏
  • 举报
回复
;with f as
(
select a from t
union
select b from t
)

declare @s varchar(1000)
select @s=isnull(@s+' ' , '')+a from f

select @s
中国风 2011-11-10
  • 打赏
  • 举报
回复
use Tempdb
go
SET NOCOUNT ON;
--> -->

if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([a] int,[b] int)
Insert #T
select 1,2 union all
select 2,3 union all
select 4,5
Go

declare @s nvarchar(4000)
set @s=''
select @s=@s+' '+RTRIM(a)
from (select a from #T
union
select b from #T
)t
order by a

print ltrim(@s)
/**/
1 2 3 4 5
*/

Select ' '+lTRIM(a)
FROM
(SELECT a from #T
UNION
Select b from #T)t FOR XML PATH('')
/*
1 2 3 4 5
*/
中国风 2011-11-10
  • 打赏
  • 举报
回复
declare @s nvarchar(4000)
set @s=''
select @s=@s+' '+a
from (select a from t
union
select b from t
)t
order by a

print ltrim(@s)

34,873

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧