sql >> Database >  >> RDS >> Sqlserver

Hoe tekenreeksen van meerdere rijen in één kolom + inner join in één query samen te voegen

Hier is de werkende SQL Fiddle:http://sqlfiddle.com/#!3/3597a/3

Hier is de daadwerkelijk werkende 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

Maak een tabel en vul gegevens in

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 uitvoeren

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

Bekijk resultaten.

TASKID  COMMENTS    TIMESPENT
111754  C1,C2,C3    84


  1. PostgreSQL Logische Replicatie Gotchas

  2. Forken of niet forken?

  3. Postgres-versies zijn niet compatibel

  4. Android MySQL-bewerkingen op afstand met behulp van een webservice met php