如何在一个查询中连接一列中多行的字符串+内部连接

How to concatenate strings from multiple rows in one column + inner join in one query(如何在一个查询中连接一列中多行的字符串+内部连接)
本文介绍了如何在一个查询中连接一列中多行的字符串+内部连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,结果如下:查询:

I have a query with the following result: query:

SELECT Tasks.TaskId, Comments.Comment, comments.timespent       
FROM   comments
INNER JOIN tasks ON comments.entityid = tasks.taskid                
WHERE  ( comments.entity = 1 ) 
GROUP  BY Tasks.TaskId, Comments.Comment, comments.timespent

结果:

TaskID  Comment  TimeSpent
__________________________
111754    C1        4
111754    C2        1
111754    C3       79

请告诉我应该如何编写查询以获得如下结果:

Please tell me how should I write my query to get the result as follows:

TaskID  Comment          TimeSpent
__________________________________
111754  ,C1,C2,C3           84

提前致谢.

推荐答案

这是工作的 SQL Fiddle:http://sqlfiddle.com/#!3/3597a/3

Here's the working SQL Fiddle: http://sqlfiddle.com/#!3/3597a/3

这是实际工作的 SQL.

Here's the actual working SQL.

SELECT Tasks.TaskId, SUBSTRING(
(SELECT ',' + Comments.Comment
FROM Comments
INNER JOIN tasks ON comments.entityid = tasks.taskid
FOR XML PATH('')),2,200000) AS Comments
, SUM(comments.timespent) AS TimeSpent      
FROM   comments
INNER JOIN tasks ON comments.entityid = tasks.taskid                
WHERE  ( comments.entity = 1 ) 
GROUP  BY Tasks.TaskId

创建表并填充数据

CREATE TABLE Tasks
(
  TaskID NVARCHAR(20) NOT NULL,
);

CREATE TABLE Comments
( 
  Entity  INT NOT NULL,
  EntityID NVARCHAR(20) NOT NULL,
  Comment NVARCHAR(50) NOT NULL,
  TimeSpent INT NOT NULL
);


INSERT INTO Tasks VALUES
( '111754' );

INSERT INTO Comments VALUES
(1,'111754', 'C1',4 ),
(1,'111754', 'C2',1 ),
(1,'111754', 'C3',79 );

执行SQL

SELECT Tasks.TaskId, SUBSTRING(
(SELECT ',' + Comments.Comment
FROM Comments
INNER JOIN tasks ON comments.entityid = tasks.taskid
FOR XML PATH('')),2,200000) AS Comments
, SUM(comments.timespent) AS TimeSpent     
FROM   comments
INNER JOIN tasks ON comments.entityid = tasks.taskid                
WHERE  comments.entity = 1 
GROUP  BY Tasks.TaskId

查看结果.

TASKID  COMMENTS    TIMESPENT
111754  C1,C2,C3    84

这篇关于如何在一个查询中连接一列中多行的字符串+内部连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)