我正在尝试为驱动器记录分配给驱动器的多个其他记录创建其他列。在我附带的屏幕截图中,您可以看到有三个驱动器,其中所有数据都是常量,但每个驱动器都分配了多个激励。
PIVOT
功能是否可以为奖励创建额外的列?我不是在寻找动态的东西,我可以在最多4个额外的列上进行硬编码,以便为一个驱动器分配五个激励空间。
我希望我的结果看起来像是:
最后一栏是我如何使用For XML Path来完成它,但它并不完全是我想要的。
这是我的SQL语句:
Select
DM.DriveID [DriveID],
DM.FromDateTime [FromDateTime],
Case When DM.OwnerType = 0 Then Acct.Name Else CD.DescLong End As [OwnerName],
Acct.AccountID [AcctID],
Inc.Description [Incentive],
Stuff ((Select ', ' + isnull(EM.Description,'')
From Production.[dbo].EquipmentMaster EM
Inner Join Production.[dbo].EquipmentDetail ED On EM.EquipmentID = ED.EquipmentID And EM.EquipmentType=3
Where ED.DriveID = DM.DriveID
For XML PATH(''), TYPE).value('.', 'varchar(max)')
,1, 2, '') as [XML_Incentives]
From
Production.[dbo].rpt_DriveMaster DM
Left Outer Join Production.[dbo].rpt_Accounts Acct on DM.AccountID=Acct.AccountID
Inner Join Production.[dbo].rpt_CenterDetail CD on DM.CenterID=CD.CenterID
Left Outer Join Production.[dbo].OBI_Incentives Inc on DM.DriveID=Inc.DriveID
Where
DM.DriveID in (658946,597611,651136)
我正在查看标记为重复时提供的链接,但几乎就像读希腊语一样。我正在尝试修改我的SQL以使用它作为基础,但没有太多运气:
是否有机会就如何运作提供指导?
Select
*
From
( Select
DM.DriveID [DriveID],
DM.FromDateTime [FromDateTime],
Case When DM.OwnerType = 0 Then Acct.Name Else CD.DescLong End As [OwnerName],
Acct.AccountID [AcctID],
Inc.Description [Incentive1],
null [Incentive2],
null [Incentive3],
null [Incentive4],
null [Incentive5]
From
Production.[dbo].rpt_DriveMaster DM
Left Outer Join Production.[dbo].rpt_Accounts Acct on DM.AccountID=Acct.AccountID
Inner Join Production.[dbo].rpt_CenterDetail CD on DM.CenterID=CD.CenterID
Left Outer Join Production.[dbo].OBI_Incentives Inc on DM.DriveID=Inc.DriveID
Where
DM.DriveID in (658946,597611,651136)
) as P
Pivot (
min(P.[Incentive])
for P.[DriveID] in ([Incentive1], [Incentive2], [Incentive3])
) as PIV