Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Cara menggabungkan string dari beberapa baris dalam satu kolom + gabungan dalam dalam satu kueri

Inilah SQL Fiddle yang berfungsi:http://sqlfiddle.com/#!3/3597a/3

Inilah SQL yang sebenarnya berfungsi.

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

Membuat Tabel dan Mengisi Data

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 );

Jalankan 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

Lihat Hasil.

TASKID  COMMENTS    TIMESPENT
111754  C1,C2,C3    84


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Apakah NOLOCK default untuk pernyataan SELECT di SQL Server 2005?

  2. Bagaimana cara memperbarui Kolom Identitas di SQL Server?

  3. Batasan klausa IN di Sql Server

  4. Cara Mengonversi Huruf Besar ke Huruf Kecil di SQL Server – LOWER()

  5. Dukungan SQL 2008 HierarchyID di NHibernate