我正在我的存储过程中执行一个数据透视操作,如下所示,但是当我将它用于报告时,它会影响性能。
是否有任何方式/替代此枢轴操作以提高性能?或者我可以为此申请索引吗?
SELECT colId,colSequence,colDescription,
ISNULL([1],0) AS 'IESO',ISNULL([2],0) AS 'RFRC',ISNULL([3],0) AS 'EAL',ISNULL([4],0) AS 'HNS',ISNULL([5],0) AS 'PTE',ISNULL([6],0) AS 'EOC',ISNULL([7],0) AS 'MU'
FROM
(
SELECT PF.FeatureId,PF.Sequence,PF.[Description],PTB.BenefitId,
FROM PSP.table1 PF
LEFT JOIN PSP.table2 PTB ON PF.FeatureId = PTB.FeatureId
left JOIN PSP.table3 PO ON PO.productID = PF.productId
WHERE PF.ProductId = @ProductId AND PF.IsDeleted = 0
) PS
PIVOT
(
MAX (BenefitId)
FOR BenefitId IN
( [1],[2],[3],[4],[5],[6],[7])
) AS pvt
ORDER BY colSequence
答案 0 :(得分:0)
您的查询使用left JOIN PSP.table3 PO
,但此表格不会显示在子查询的SELECT
字段列表中。
如果此表无效,您可以将其删除,以便获得操作。
检查查询表上的索引,但我认为您FeatureId
上的索引与productID
字段上的索引
答案 1 :(得分:0)
不确定它是否超级有益,但您可以使用聚合案例表达式来获取所需的值,而不是PIVOT。您可以使用OUTER APPLY,这样您就不必按3列分组,其中一列是描述列。
SELECT colId = PF.FeatureId,
colSequence = PF.Sequence,
colDescription = PF.[Description],
PTB.*
FROM PSP.table1 PF
OUTER APPLY (
SELECT 'IESO' = COUNT(CASE WHEN BenefitId = 1 THEN 1 END),
'RFRC' = COUNT(CASE WHEN BenefitId = 2 THEN 1 END),
'EAL' = COUNT(CASE WHEN BenefitId = 3 THEN 1 END),
'HNS' = COUNT(CASE WHEN BenefitId = 4 THEN 1 END),
'PTE' = COUNT(CASE WHEN BenefitId = 5 THEN 1 END),
'EOC' = COUNT(CASE WHEN BenefitId = 6 THEN 1 END),
'MU' = COUNT(CASE WHEN BenefitId = 7 THEN 1 END)
FROM PSP.table2 PTB
WHERE PF.FeatureId = PTB.FeatureId
) PTB
WHERE PF.ProductId = @ProductId
AND PF.IsDeleted = 0