帮忙写个SQL

十三- 2015-09-15 09:35:28

表结构如下:
id attID AttVal
1 1 a
2 1 b
3 1 c



现要如下结果 (str 是 AttVal 和id 组成字符串)
attid str
1 a|b|c,1|2|3
...全文
99 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
-小蕾- 2015-09-15
  • 打赏
  • 举报
回复
引用 4 楼 qq_17482963 的回复:
with tb(id,attID,AttVal)
as
(     
select 1,1,'a' union all
select 2,1,'b' union all
select 3,1,'c' union all
select 4,2,'d' union all
select 5,2,'e'
)
select c.attID,
str=STUFF((select '|'+AttVal from tb b where b.attID=c.attID for XML path('')),1,1,'')+','+STUFF((select '|'+convert(nvarchar(20),id) from tb a where a.attID=c.attID for xml path('')),1,1,'') from tb c group by attID
結果
attID       str
----------- --------------------
1           a|b|c,1|2|3
2           d|e,4|5
+1
十三- 2015-09-15
  • 打赏
  • 举报
回复
引用 4 楼 qq_17482963 的回复:
with tb(id,attID,AttVal)
as
(     
select 1,1,'a' union all
select 2,1,'b' union all
select 3,1,'c' union all
select 4,2,'d' union all
select 5,2,'e'
)
select c.attID,
str=STUFF((select '|'+AttVal from tb b where b.attID=c.attID for XML path('')),1,1,'')+','+STUFF((select '|'+convert(nvarchar(20),id) from tb a where a.attID=c.attID for xml path('')),1,1,'') from tb c group by attID
結果
attID       str
----------- --------------------
1           a|b|c,1|2|3
2           d|e,4|5
谢了..
qq_17482963 2015-09-15
  • 打赏
  • 举报
回复
with tb(id,attID,AttVal)
as
(     
select 1,1,'a' union all
select 2,1,'b' union all
select 3,1,'c' union all
select 4,2,'d' union all
select 5,2,'e'
)
select c.attID,
str=STUFF((select '|'+AttVal from tb b where b.attID=c.attID for XML path('')),1,1,'')+','+STUFF((select '|'+convert(nvarchar(20),id) from tb a where a.attID=c.attID for xml path('')),1,1,'') from tb c group by attID
結果
attID       str
----------- --------------------
1           a|b|c,1|2|3
2           d|e,4|5
十三- 2015-09-15
  • 打赏
  • 举报
回复
再写全一点

表结构如下:
id    attID      AttVal     
1        1          a
2        1          b
3        1          c
4        2          d
5        2          e

现要如下结果  (str 是 AttVal 和id 组成字符串)
attid         str
  1           a|b|c,1|2|3
  2           d|e,4|5

十三- 2015-09-15
  • 打赏
  • 举报
回复
引用 1 楼 chenbin_90 的回复:
没看懂楼主是想要什么效果 现要如下结果 (str 是 AttVal 和id 组成字符串) attid str 1 a|b|c,1|2|3 查询后出现的数据,是只要这一条,还是后面还有很多条,那么后面的数据又是怎样的?
attid 相同的 合并为一条
仰望那天空 2015-09-15
  • 打赏
  • 举报
回复
没看懂楼主是想要什么效果 现要如下结果 (str 是 AttVal 和id 组成字符串) attid str 1 a|b|c,1|2|3 查询后出现的数据,是只要这一条,还是后面还有很多条,那么后面的数据又是怎样的?

34,576

社区成员

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

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