对sql查询中的项目进行分组
我有一个表,其中包含类似(在sql server 2000中)的列,
MailCode Mode Name Group
-------- ----- --------- -------
1 1 abc 0
1 1 def 0
1 1 qwe 1
2 2 aaw 0
2 2 aad 0
我想根据其余字段对名称字段进行分组,以便结果看起来像这样(应该只有一个唯一的mailCode、模式和组组合)
MailCode Mode Names Group
--------- ------ ------------ -------
1 1 abc, def 0
1 1 qwe 1
2 2 aaw, aad 0
如何我为此创建了 sql 查询?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到了类似的问题,我必须在选择中连接一个字段,当时我的解决方案是创建一个返回结果的过程,并像这样调用它
select x as field1, y as field2, dbo.procedure as field3
I had a similar problem where I had to concatenate a field in the select, my solution at the time was to create a procedure that returned the result and called it like this
select x as field1, y as field2, dbo.procedure as field3
SQL Server 2000 解决方案
幸运的是,2000 年支持 COALESCE< /a>,因此您可以使用 COALESCE 技巧创建逗号分隔的值列表,在此链接中演示。由于变量的使用,您需要创建一个函数/过程并在主查询中调用它。基本上,只需将下面查询中的 STUFF() 替换为函数调用即可。
SQL Server 2005+ 解决方案:
SQL Server 2000 solution
Luckily, COALESCE is supported in 2000, so you can use the COALESCE trick to create a comma delimited list of values, demonstrated in this link. Because of the variable usage, you'll need to create a function/procedure and call it within the main query. Basically, just replace the STUFF() in the query below with the function call.
SQL Server 2005+ solution:
我想不出一个简单的查询可以得到你正在寻找的结果,但是沿着这些思路的一些逻辑应该可以让你到达你想要的地方:
公平警告,SQL 中的循环往往会对性能产生巨大的影响。大型数据集。不幸的是我不知道更好的方法来做到这一点。
I can't think of a simple query that will get the result you're looking for, but some logic along these lines should get you where you want:
Fair waring, looping in SQL tends to have a huge performance hit when it comes to large datasets. I unfortunately don't know a better way to do it.