TSQL 中的合并和透视
我无法弄清楚如何合并或旋转 SQL 记录集,如下所示:
ID VALUE GROUP
3 John 18
4 Smith 18
5 Microsoft 18
3 Randy 21
4 Davis 21
5 IBM 21
etc
并且我想要这样的格式,
NEWVALUE GROUP
Smith, John (Microsft) 18
Davis, Randy (IBM) 21
感谢您的任何建议和帮助!
I am having trouble figuring out how to coalesce or pivot on a SQL recordset that looks like this:
ID VALUE GROUP
3 John 18
4 Smith 18
5 Microsoft 18
3 Randy 21
4 Davis 21
5 IBM 21
etc
and I want formatted like this
NEWVALUE GROUP
Smith, John (Microsft) 18
Davis, Randy (IBM) 21
thanks for any suggestions and help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是我所做的,我希望它适合你
This is what i done, i hope it fits for you
如果每个
_group
始终有一组三个硬编码的ID
,则可以使用:If you always have a set of three hardcoded
ID
's for each_group
, you can just use:您需要的不是旋转查询,而是带有分组依据和聚合字符串连接函数的简单选择。 但我不记得 tsql 中的确切函数。
更新:tsql 中没有聚合连接函数,但从 sql2005 开始,您可以编写自己的扩展来实现此类函数。 谷歌搜索上有很多示例:tsql 2005 concatenationaggregate example。
What you need is not pivoted query but a simple select with group by and an aggregate string concatenation function. But i don't remember the exact function in tsql.
Update: there is no aggregate concatenation function in tsql but since sql2005 you can write your own extension to implement such function. There is plenty of examples on google search for: tsql 2005 concatenation aggregate example.
这有点做作,但我认为它对于小数据集应该工作得相当好。 如果您有大量数据,则需要创建游标和循环。
This is a little hokey, but I think it should work reasonably well for a small data set. If you've got a lot of data you need to create a cursor and a loop.