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

Pivot dinamis SQL untuk tujuan

CREATE TABLE #tt(id INT IDENTITY(1,1) PRIMARY KEY,EmpCode INT,Empname VARCHAR(2566),Goals VARCHAR(256));
INSERT INTO #tt(EmpCode,Empname,Goals)VALUES
    (101,'kiran','readsql'),
    (101,'kiran','coding'),
    (101,'kiran','readcss'),
    (102,'rohit','coding'),
    (102,'rohit','readjava'),
    (103,'pradi','do nothing');

DECLARE @goal_cols NVARCHAR(MAX)=STUFF((
    SELECT DISTINCT N',Goal'+CAST(ROW_NUMBER()OVER(PARTITION BY empcode ORDER BY id) AS VARCHAR(3))
    FROM #tt
    FOR XML PATH('')
    ),1,1,''
);

DECLARE @stmt NVARCHAR(MAX)=N'
    SELECT *    
    FROM (
            SELECT 
                EmpCode,Empname,Goals,
                goal_id=''Goal''+CAST(ROW_NUMBER()OVER(PARTITION BY empcode ORDER BY id) AS VARCHAR(3))
            FROM 
                #tt
        ) AS s
        PIVOT(MAX(Goals) FOR goal_id IN ('[email protected]_cols+')) AS p
    ORDER BY EmpCode;';

EXECUTE sp_executesql @stmt;

DROP TABLE #tt;

Hasil:

+---------+---------+------------+----------+---------+
| EmpCode | Empname |   Goal1    |  Goal2   |  Goal3  |
+---------+---------+------------+----------+---------+
|     101 | kiran   | readsql    | coding   | readcss |
|     102 | rohit   | coding     | readjava | NULL    |
|     103 | pradi   | do nothing | NULL     | 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. SQL Server:Ekstrak Tabel Meta-Data (deskripsi, bidang dan tipe datanya)

  2. Menyimpan data UTF-16/Unicode di SQL Server

  3. Bagaimana cara mendapatkan perbedaan antara dua baris untuk bidang kolom?

  4. Bagaimana cara mendekripsi kata sandi dari SQL server?

  5. Kunci asing yang fleksibel