gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:37:17 25 4
gpt4 key购买 nike

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

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

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

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

提前致谢。

最佳答案

这是正在运行的 SQL Fiddle:http://sqlfiddle.com/#!3/3597a/3

这是实际运行的 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

关于sql-server - 如何在一个查询中连接一列中多行的字符串 + 内部联接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21387696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com