SQLServer查询优化

时间:2017-06-23 13:53:46

标签: sql sql-server

我正在使用SQL Server 2016.以下查询非常慢(大约需要40秒):

SELECT * FROM
(SELECT * FROM [dbo].[CR_Data1]) AS main
UNPIVOT
([Dates] FOR [Tags] IN ([Submitted_on], [Analyzed_on], [Approved_on], 
[Postponed_on], [Assigned_on], [Opened_on], [Verified_on], [Rejected_on], 
[Resolved_on],  [Closed_on], [Cancelled_on], [Deferred_on], [Duplicate_on])
) AS b inner join CR_Data1 a on b.id=a.id

如何优化执行? (添加索引或者可能重写它?)

请告知。

enter image description here

1 个答案:

答案 0 :(得分:0)

我会尝试将其写成:

select m.*, v.*
from [dbo].[CR_Data1] m cross apply
     (values ('Submitted_on', [Submitted_on]), 
             ('Analyzed_on', [Analyzed_on]),
             ('Approved_on', [Approved_on]), 
             ('Postponed_on', [Postponed_on]), 
             ('Assigned_on', [Assigned_on]),
             ('Opened_on', [Opened_on]),
             ('Verified_on', [Verified_on]),
             ('Rejected_on', [Rejected_on]),
             ('Resolved_on', [Resolved_on]),
             ('Closed_on', [Closed_on]),
             ('Cancelled_on', [Cancelled_on]),
             ('Deferred_on', [Deferred_on]),
             ('Duplicate_on', [Duplicate_on])
     ) v(tag, date);

如果我正确地阅读了查询,您似乎不需要任何加入。