如何使用自连接和分组依据编写查询?
我有以下格式的 sql server 2008 db 表 FILE_DETAILS。
ID FileName Filesize_in_MB
--------------------------------
1 a.txt 5
2 b.txt 2
3 c.txt 2
3 d.txt 4
4 e.txt 6
4 f.txt 1
4 g.txt 2
5 h.txt 8
6 i.txt 7
现在我想要获取的内容如下
ID FileName Filesize_in_MB
--------------------------------
1 a.txt 5
2 b.txt 2
3 c.txt;d.txt 6
4 e.txt;f.txt;g.txt 9
5 h.txt 8
6 i.txt 7
在上面的结果中发生的情况 ID
成为唯一键,并且 FILENAME
已附加并由 ;
分隔,并且group by ID
总和中的 FILESIZE_IN_MB
字段
我尝试使用各种组合,例如 groupby + self join,还有子查询等等 但我想我错过了一些东西。
是否可以在 SQL 查询中处理这个问题?
提前致谢
I have sql server 2008 db table FILE_DETAILS in following format.
ID FileName Filesize_in_MB
--------------------------------
1 a.txt 5
2 b.txt 2
3 c.txt 2
3 d.txt 4
4 e.txt 6
4 f.txt 1
4 g.txt 2
5 h.txt 8
6 i.txt 7
now what i want to fetch is as bellow
ID FileName Filesize_in_MB
--------------------------------
1 a.txt 5
2 b.txt 2
3 c.txt;d.txt 6
4 e.txt;f.txt;g.txt 9
5 h.txt 8
6 i.txt 7
In above results what happens ID
became unique key and FILENAME
has get attached and separated by ;
and also FILESIZE_IN_MB
field in sum of group by ID
I tried with various combination like groupby + self join, also sub queries and all that
but i think i missing something.
is it possible to handle this in SQL query?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
这里有更多信息:
将多行连接成一个文本字符串?
Try this:
Here's some more information:
Concatenate many rows into a single text string?
您应该能够使用
group by
来完成此操作。可以使用sum
作为聚合器来聚合Filesize_IN_MB
。但是,要聚合FileName
,您可能需要创建一个 AGGREGATE在 SQL SERVER 2008R2 中。这将允许您使用Concatenate
作为聚合函数。还有另一种聚合串联 看起来相当简单,但我没试过。
You should be able to do this using a
group by
. AggregatingFilesize_IN_MB
can be done usingsum
as aggregator. However, to aggregateFileName
you may need to create an AGGREGATE in SQL SERVER 2008R2. This will allow you to useConcatenate
as an aggregation function.There is another way of aggregate concatenation which seems fairly simple but I haven't tried.