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

Sql menggabungkan data baris ke kolom

DECLARE @t TABLE (
    TransNo VARCHAR(20),
    Serial INT,
    Project INT
)

INSERT INTO @t (TransNo, Serial, Project)
VALUES
    ('A00000000000001', 1, 100),
    ('A00000000000001', 2, 200),
    ('A00000000000001', 3, 201),
    ('A00000000000001', 4, 101),
    ('A00000000000002', 1, 100),
    ('A00000000000002', 2, 101),
    ('A00000000000003', 1, 100),
    ('A00000000000003', 2, 200),
    ('A00000000000004', 1, 200),
    ('A00000000000004', 2, 100),
    ('A00000000000005', 1, 101),
    ('A00000000000005', 2, 100)

SELECT *, CProject = (
    SELECT DISTINCT [text()] = t2.Project
    FROM @t t2
    WHERE t2.TransNo = t1.TransNo
    ORDER BY t2.Project
    FOR XML PATH('')
)
FROM @t t1

keluaran -

TransNo              Serial      Project     CProject
-------------------- ----------- ----------- --------------
A00000000000001      1           100         100101200201
A00000000000001      2           200         100101200201
A00000000000001      3           201         100101200201
A00000000000001      4           101         100101200201
A00000000000002      1           100         100101
A00000000000002      2           101         100101
A00000000000003      1           100         100200
A00000000000003      2           200         100200
A00000000000004      1           200         100200
A00000000000004      2           100         100200
A00000000000005      1           101         100101
A00000000000005      2           100         100101

dengan [text()] -

100101200201

tanpa [text()] -

<Project>100</Project><Project>101</Project><Project>200</Project><Project>201</Project>

lebih detail - http:// www.codeproject.com/Articles/691102/String-Aggregation-in-the-World-of-SQL-Server

pembaruan -

SELECT *, CProject = (
    SELECT [text()] = t2.Project
    FROM (
        SELECT t2.Project, Serial = MIN(t2.Serial)
        FROM @t t2
        WHERE t2.TransNo = t1.TransNo
        GROUP BY t2.Project
    ) t2
    ORDER BY t2.Serial
    FOR XML PATH('')
)
FROM @t t1


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Menerapkan Keamanan Tingkat Baris di SQL Server 2008

  2. SSMS 2008 mengubah karakter kontrol menjadi spasi saat menggunakan 'Hasil ke Kotak'

  3. @@ROWCOUNT – Dapatkan Jumlah Baris yang Dipengaruhi oleh Pernyataan Terakhir di SQL Server

  4. Unicode SQL Query W/ Parameter bukan N Prefix

  5. TSQL - Apakah mungkin untuk menentukan urutan pengurutan?