求一Sql语句

xinmeng08 2010-03-13 11:10:15
比如数据库里面字段
字段a 字段b 字段c
1 123 a
2 234 b
3 345 c
4 456 d
5 234 e
6 345 f
7 234 g
我要获取如下字段信息
1 123 a
2 234 b,e,g
3 345 c
4 456 d
...全文
112 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xinmeng08 2010-03-14
  • 打赏
  • 举报
回复
d,e都是随便字符串的
yhtapmys 2010-03-14
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 josy 的回复:]
引用 5 楼 xinmeng08 的回复:
楼上的大哥果然是高手,问题是我这里还有几个字段比如d e,如果这样Group By不了


d,e的数据是怎么样的,你要什么结果,拿点数据说明一下
[/Quote]

up
百年树人 2010-03-13
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 xinmeng08 的回复:]
楼上的大哥果然是高手,问题是我这里还有几个字段比如d e,如果这样Group By不了
[/Quote]

d,e的数据是怎么样的,你要什么结果,拿点数据说明一下
xinmeng08 2010-03-13
  • 打赏
  • 举报
回复
d,e都是NVarchar
xinmeng08 2010-03-13
  • 打赏
  • 举报
回复
楼上的大哥果然是高手,问题是我这里还有几个字段比如d e,如果这样Group By不了
百年树人 2010-03-13
  • 打赏
  • 举报
回复
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([a] int,[b] int,[c] varchar(1))
insert [tb]
select 1,123,'a' union all
select 2,234,'b' union all
select 3,345,'c' union all
select 4,456,'d' union all
select 5,234,'e' union all
select 6,345,'f' union all
select 7,234,'g'

---查询---
select
a=row_number() over(order by getdate()),
b,
c=stuff((select ','+c from tb where b=t.b for xml path('')),1,1,'')
from
tb t
group by
b


---结果---
a b c
-------------------- ----------- ----------------

1 123 a
2 234 b,e,g
3 345 c,f
4 456 d

(4 行受影响)
bancxc 2010-03-13
  • 打赏
  • 举报
回复
合并列 ..
xinmeng08 2010-03-13
  • 打赏
  • 举报
回复
补充:
用存储过程的...
jiangshun 2010-03-13
  • 打赏
  • 举报
回复
合并字符串

34,576

社区成员

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

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