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

Bagaimana cara menggabungkan data dari beberapa baris menjadi satu?

Menggunakan PIVOT Anda dapat melakukan hal berikut

With SampleData AS 
(
SELECT 'Team1' as Team , '[email protected]' as email, 'A' as Groups
UNION SELECT 'Team1' as Team , '[email protected]' as email, 'B' as Groups
UNION SELECT 'Team1' as Team , '[email protected]' as email, 'C' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'A' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'B' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'C' as Groups
)
SELECT Team, A, B,C FROM 
(SELECT * FROM SampleData) source
PIVOT
(MAX(email) FOR Groups IN ([A], [B], [C]) )as pvt

Menghasilkan

Team  A                B                C
----- ---------------- ---------------- ----------------
Team1 [email protected] [email protected] [email protected]
Team2 [email protected] [email protected] [email protected]

Lihat contoh Data.SE yang berfungsi

Dalam DB yang tidak mendukung PIVOT, Anda dapat melakukan beberapa penggabungan ke tabel Anda. Meskipun Anda mungkin menginginkannya, karena seperti yang ditunjukkan GBN, karena kami tidak menggunakan agregat.

With SampleData AS 
(
SELECT 'Team1' as Team , '[email protected]' as email, 'A' as Groups
UNION SELECT 'Team1' as Team , '[email protected]' as email, 'B' as Groups
UNION SELECT 'Team1' as Team , '[email protected]' as email, 'C' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'A' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'B' as Groups
UNION SELECT 'Team2' as Team , '[email protected]' as email, 'C' as Groups
)

SELECT 
    source.Team,
    A.email,
    B.email,
    C.email
FROM 
    (SELECT DISTINCT TEAM From SampleData) source
    LEFT JOIN SampleData A 
    ON source.Team = A.Team
     AND A.GROUPS = 'A'
    LEFT JOIN SampleData B 
    ON source.Team = B.Team
    AND B.GROUPS = 'B'
    LEFT JOIN SampleData C 
    ON source.Team = C.Team
    AND C.GROUPS = 'C'

Lihat contoh Data.SE yang berfungsi




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Menggunakan sp_help_jobschedule di SQL Server

  2. SQL - Pivot table dan group dengan tidak bekerja

  3. Gunakan XEvent Profiler untuk menangkap kueri di SQL Server

  4. Apa manfaat menggunakan SET XACT_ABORT ON dalam prosedur tersimpan?

  5. Tidak dapat menjatuhkan objek karena direferensikan oleh batasan KUNCI ASING - Tutorial SQL Server / TSQL Bagian 74