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

Gabung tabel dengan baris

Jika Anda hanya memiliki beberapa nomor posisi, Anda dapat melakukannya dengan PIVOT kata kunci

select
    UserID,
    UserName,
    [1] as Position1,
    [2] as Position2,
    [3] as Position3
from
(
    select
        U.UserID, U.UserName, P.PositionName,
        row_number() over (partition by U.UserID order by P.PositionName) as RowNum
    from Positions_Users as PU
        inner join Positions as P on P.PositionID = PU.PositionID
        inner join Users as U on U.UserID = PU.UserID
) as P
    pivot
    (
        min(P.PositionName)
        for P.RowNum in ([1], [2], [3])
    ) as PIV

SQL FIDDLE

Namun, jika Anda ingin memiliki jumlah kolom yang dinamis, Anda harus menggunakan SQL dinamis, seperti ini

declare @stmt nvarchar(max), @stmt_columns1 nvarchar(max), @stmt_columns2 nvarchar(max)
declare @Temp_Data table (RowNum nvarchar(max))

insert into @Temp_Data
select distinct row_number() over (partition by U.UserID order by P.PositionName) as RowNum
from Positions_Users as PU
    inner join Positions as P on P.PositionID = PU.PositionID
    inner join Users as U on U.UserID = PU.UserID

select @stmt_columns1 = stuff((select ', [' + RowNum + ']' from @Temp_Data for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '')
select @stmt_columns2 = stuff((select ', [' + RowNum + '] as Position' + RowNum from @Temp_Data for xml path(''), type).value('.', 'nvarchar(max)'), 1, 2, '')

select @stmt = '
select
    UserID,
    UserName,' + @stmt_columns2 + '
from
(
    select
        U.UserID, U.UserName, P.PositionName,
        row_number() over (partition by U.UserID order by P.PositionName) as RowNum
    from Positions_Users as PU
        inner join Positions as P on P.PositionID = PU.PositionID
        inner join Users as U on U.UserID = PU.UserID
) as P
    pivot
    (
        min(P.PositionName)
        for P.RowNum in (' + @stmt_columns1 + ')
    ) as PIV'

exec sp_executesql @stmt = @stmt

SQL FIDDLE




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Apa itu file MDF?

  2. Sisipkan Massal Di SQL Server CE

  3. Cara Menghubungkan ke Beberapa Server SQL dalam Satu Klik (Grup Server Terdaftar) - Tutorial SQL Server / TSQL Bagian 5

  4. Kembalikan nilai dari perintah Sisipkan SQL Server menggunakan c #

  5. Bagaimana cara menambahkan Failover Partner ke string koneksi di VB.NET