Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
dynamic pivot
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
--Sql Server 2014 Express Edition --Batches are separated by 'go' create table Employee(Id int primary key,Name varchar(255)); create table EquipMent(Id int primary key ,EquipmentName varchar(255)); create table EquipmentMapping(Id int primary key,EmployeeId varchar(255),EquipmentId int); INSERT INTO Employee (Id,Name) values (1,'Jhon'), (2,'Max'); insert into EquipMent (Id,EquipmentName) values (1,'Hammer'), (2,'Axe'), (3,'Screw Driver'); insert into EquipmentMapping (Id,EmployeeId,EquipmentId) values (1,1,1), (2,1,2), (3,2,1), (4,2,3); select EM.Id,EM.EmployeeId,EM.EquipmentId from EquipmentMapping EM ---------------- DECLARE @DynamicPivotQuery AS NVARCHAR(MAX), @PivotColumnNames AS NVARCHAR(MAX), @PivotSelectColumnNames AS NVARCHAR(MAX) --Get distinct values of the PIVOT Column SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','') + QUOTENAME(EquipmentId) FROM (SELECT DISTINCT EquipmentId FROM EquipmentMapping) AS EquipmentId --Get distinct values of the PIVOT Column with isnull SELECT @PivotSelectColumnNames = ISNULL(@PivotSelectColumnNames + ',','') + QUOTENAME(EquipmentId) +' AS ' + QUOTENAME('Equipment' + convert(varchar(10), EquipmentId) + 'id') FROM (SELECT DISTINCT EquipmentId FROM EquipmentMapping) AS EquipmentId --Prepare the PIVOT query using the dynamic SET @DynamicPivotQuery = N'SELECT EmployeeId, ' + @PivotSelectColumnNames + ' From ( select EmployeeId, EquipmentId from EquipmentMapping ) x PIVOT(MAX(EquipmentId) FOR EquipmentId IN (' + @PivotColumnNames + ')) AS PVTTable' --Execute the Dynamic Pivot Query EXEC sp_executesql @DynamicPivotQuery
View schema
Execution time: 0,02 sec, rows selected: 13, rows affected: 9, absolute service time: 0,17 sec
edit mode
|
history
|
discussion
Id
EmployeeId
EquipmentId
1
1
1
1
2
2
1
2
3
3
2
1
4
4
2
3
EmployeeId
Equipment1id
Equipment2id
Equipment3id
1
1
1
2
NULL
2
2
1
NULL
3