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

Pivot dan koma nilai yang dipisahkan

Coba yang ini -

Kueri:

IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL
   DROP TABLE #temp

CREATE TABLE #temp
(
        [user] VARCHAR(10)
      , Category VARCHAR(10)
      , [Date] DATETIME
)

INSERT INTO #temp ([user], Category, [Date])
VALUES 
    ('Jack',  'Shoes', '20110101'),
    ('Jack',  'Tie',   '20110102'),
    ('Jack',  'Glass', '20110303'),
    ('Peggy', 'Shoe',  '20120202'),
    ('Peggy', 'Skirt', '20131202')

DECLARE @Columns NVARCHAR(MAX)

SELECT @Columns = STUFF((
    SELECT DISTINCT
        ',[' + 'Category' + CAST(
        ROW_NUMBER() OVER (PARTITION BY t.[user] ORDER BY (SELECT 1)) AS VARCHAR(3)) + ']'
    FROM #temp t
    FOR XML PATH (''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 1, '')

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
SELECT [user], ' + @Columns + ', Dates 
FROM (
    SELECT 
          t.[user]
        , t.category
        , rn = ''Category'' + CAST(ROW_NUMBER() OVER (PARTITION BY t.[user] ORDER BY (SELECT 1)) AS VARCHAR(3))
        , Dates = STUFF((
              SELECT '', '' + CONVERT(VARCHAR(10), t2.[Date], 103)
              FROM #temp t2
              WHERE t2.[user] = t.[user]
              FOR XML PATH(''''), TYPE).value(''.'', ''VARCHAR(MAX)''), 1, 2, '''')  
    FROM #temp t
) t3 
PIVOT (
    MAX(category) 
    FOR rn IN (' + @Columns + ')
) p'

PRINT @SQL

EXECUTE sys.sp_executesql @SQL

Keluaran:

SELECT [user], [Category1],[Category2],[Category3], Dates 
FROM (
    SELECT 
          t.[user]
        , t.category
        , rn = 'Category' + CAST(ROW_NUMBER() OVER (PARTITION BY t.[user] ORDER BY (SELECT 1)) AS VARCHAR(3))
        , Dates = STUFF((
              SELECT ', ' + CONVERT(VARCHAR(10), t2.[Date], 103)
              FROM #temp t2
              WHERE t2.[user] = t.[user]
              FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 2, '')  
    FROM #temp t
) t3 
PIVOT (
    MAX(category) 
    FOR rn IN ([Category1],[Category2],[Category3])
) p

Hasil:

user       Category1  Category2  Category3  Dates
---------- ---------- ---------- ---------- -------------------------------------
Jack       Shoes      Tie        Glass      01/01/2011, 02/01/2011, 03/03/2011
Peggy      Shoe       Skirt      NULL       02/02/2012, 02/12/2013



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Tidak dapat meneruskan parameter input ke prosedur tersimpan

  2. Cara Menampilkan Tanggal dalam Format Jerman di SQL Server (T-SQL)

  3. Pencarian teks lengkap diinstal atau tidak

  4. Jenis teks, nteks, dan data gambar> tidak dapat dibandingkan atau diurutkan, kecuali jika menggunakan operator IS NULL atau LIKE>

  5. Tambahkan baris ringkasan dengan total