如何在SQL Server 2012中实现的视图中选择不同的记录作为列

时间:2018-03-16 10:33:43

标签: sql-server

考虑以下表格架构

Employee(Id int primary key,Name varchar(255))

EquipMent(Id int primary key ,EquipmentName varchar(255))

EquipmentMapping(Id int primary key,EmployeeId varchar(255),EquipmentId int)

将这些表中的以下数据视为

Employee
(Id,Name)
(1,Jhon)
(2,Max)


EquipMent
(Id,EquipmentName)
(1,Hammer)
(2,Axe)
(3,Screw Driver)


EquipmentMapping
(Id,EmployeeId,EquipmentId)
(1,1,1)
(2,1,2)
(3,2,1)

我想创建一个视图,其中包含以下模式

EmployeeEquipmentMappingView(Id int identity(1,1),EmployeeId int,Equipment1Id int,EquipMent2Id int)

这里的限制是员工不能有超过2个设备映射他。

我想在Equipment1Id和EquipMent2Id列中选择这两个映射的设备。

输出看起来像

Select * from EmployeeEquipmentMappingView
(Id ,EmployeeId ,Equipment1Id ,EquipMent2Id )
(1,1,1,2)
(2,2,1,NULL)

1 个答案:

答案 0 :(得分:0)

试试这个

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

Live sample