Share via

correlated Query-Performance Issues

jennifer zen 341 Reputation points
2021-10-11T20:27:41.37+00:00

Hello,

I am trying to do a rolling 12 month sum using correlated query as below in the script, but it takes around 1 hour to get me the results.
Can somebody help me to script it better please?

select
[SalesEndingDate],
[Level],
[OrgName],
[SiteCode],
[SiteName],
[ItemDesc],
[ItemValue]

--Calculate rolling 12 months value for each site
, (
Select Sum([ItemValue])
FROM [Sales].[dbo].[MonthlyNationalValues] as Rolling12
WHERE cite.[SiteCode] = Rolling12.[SiteCode]
AND Rolling12.[SalesEndingDate] between dateadd("m", -11, cite.[SalesEndingDate]) and cite.[SalesEndingDate]
AND cite.[SalesEndingDate] >'2020-03-31'
AND [level] in ('04SPR','03DEW','04MWRT')
AND[ItemDesc] ='SER2393'
) as [12MonthRollingItemValue]

from
[Sales].[dbo].[MonthlyNationalValues] cite

where 1=1
and [level] in ('04SPR','03DEW','04MWRT')
and [SalesEndingDate] >'2020-03-31'
and [ItemDesc] = 'SER2393'

Thanks in advance

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


1 answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,626 Reputation points
    2021-10-12T05:53:50.717+00:00

    Hi @jennifer zen ,

    Do you have the right index? Please try to create an index on the conditional column([level]、[SalesEndingDate]、[ItemDesc]) after WHERE first.

    In addition, we need you to provide the execution plan and index information on your table.

    Regards
    Echo

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.