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

Pivot baris Dinamis ke Kolom dengan parameter output?

Anda dapat melakukannya dengan mengikuti:

QUERY

CREATE PROCEDURE [dbo].[sp_test]
@AppPool AS NVARCHAR(60)
AS
DECLARE @cols   AS NVARCHAR(MAX) = '',
        @sql    AS NVARCHAR(MAX)

SELECT @cols += QUOTENAME([Name]) + ','
FROM   (SELECT DISTINCT Attribute as Name
        FROM    [dbo].[Vy_UserAccess]
        WHERE   PoolID = @AppPool
        ) a 
ORDER BY Name DESC 

SET @cols   = LEFT(@cols, LEN(@cols) - 1)   

SET @sql    = 'SELECT Users, ' + @cols + ' FROM 
    (
    SELECT [Pool],[Users],[RecNum],[Attribute],[Values] 
    FROM [dbo].[Vy_UserAccess]
     ) AS  T1
PIVOT (MAX([Values]) FOR [ATTRIBUTE] IN ('+ @cols +')) AS T2'

EXEC sp_executesql @sql, N'@AppPool NVARCHAR(60)', @AppPool

EKSEKUSI

Exec sp_test 1

QUERY DENGAN CONTOH DATA

CREATE PROCEDURE sp_test 
@AppPool AS NVARCHAR(60)
AS

CREATE TABLE #test
(
    PoolId NVARCHAR(60),
    Pool NVARCHAR(40),
    Users NVARCHAR(60),
    RecNum INT,
    Attribute NVARCHAR(40),
    [Values] NVARCHAR(20)
)
INSERT INTO #test VALUES
('1', 'FINANCE', 'User1', 2, 'DIVISION', '010'),
('1', 'FINANCE', 'User1', 1, 'COMPANY',  '1'),
('1', 'FINANCE', 'User1', 1, 'DIVISION', '050')



DECLARE @cols   AS NVARCHAR(MAX) = '',
        @sql    AS NVARCHAR(MAX)

SELECT @cols += QUOTENAME([Name]) + ','
FROM   (SELECT DISTINCT Attribute as Name
        FROM    #test
        WHERE   PoolID = @AppPool       
        ) a 
ORDER BY Name DESC                      
SET @cols   = LEFT(@cols, LEN(@cols) - 1)


SET @sql    = 'SELECT Users, ' + @cols + ' FROM 
    (
    SELECT [Pool],[Users],[RecNum],[Attribute],[Values] 
    FROM #test
     ) AS  T1
PIVOT (MAX([Values]) FOR [ATTRIBUTE] IN ('+ @cols +')) AS T2'

EXEC Sp_executesql @sql, N'@AppPool NVARCHAR(60)', @AppPool

DROP TABLE #test

KELUARAN

Users   DIVISION    COMPANY
User1   050         1
User1   010         NULL



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Perbarui kolom varbinary(MAX)

  2. Lakukan Union jika tabel dengan nama-nama ini ada

  3. Bagaimana saya bisa menanyakan budaya database (SQL Server 2005)?

  4. Mengubah Kolom yang Ada menjadi Kolom Terhitung di SQL Server (Contoh T-SQL)

  5. Perbedaan Antara sys.views, sys.system_views, &sys.all_views di SQL Server