How could optimize the following query :
SELECT
CASE WHEN COUNT(distinct t1.[datecol]) = 0
THEN 0
ELSE SUM(convert(float, Quantité)) / count(distinct t1.[datecol])
END as QTEMOY,
CASE WHEN COUNT(distinct t1.[datecol]) = 0
THEN 0
ELSE SUM(convert(float, [Prix de vente TTC])) / count(distinct t1.[datecol])
END AS CAMOY,
t1.[Code Article],
t1.[Code Structure],
t1.[Code Site]
from [Vente ] t1
outer apply
(
select distinct top 28 t2.[datecol]
from [Vente ] t2
where t2.[Code Article] = t1.[Code Article]
and t2.[Code Structure]=t1.[Code Structure]
and t2.[Code Site]=t1.[Code Site]
and not exists (SELECT [Code Article]
FROM [Promotion ]
where t2.datecol between
[Date Debut Promo] and [Date Fin Promo]and t2.[Code Article] = [Code Article] )
order by t2.[datecol] desc
) t2
where not exists (SELECT t1.[Code Article]
FROM [Promotion ]
where t1.datecol between
[Date Debut Promo] and [Date Fin Promo]and t1.[Code Article] = [Code Article] )
and (t1.[Code Article] is not null)
and (t1.[Code Structure] is not null)
and (t1.[Prix de Revient] is not null )
and t1.datecol = t2.datecol
and t1.[Code Article] in( select [Code Article] from [Reference] t )
group by t1.[Code Article],
t1.[Code Structure],
t1.[Code Site]
The query took hours executed HOW TO OPTIMIZE it?
SELECT
CASE WHEN COUNT(distinct t1.[datecol]) = 0
THEN 0
ELSE SUM(convert(float, Quantité)) / count(distinct t1.[datecol])
END as QTEMOY,
CASE WHEN COUNT(distinct t1.[datecol]) = 0
THEN 0
ELSE SUM(convert(float, [Prix de vente TTC])) / count(distinct t1.[datecol])
END AS CAMOY,
t1.[Code Article],
t1.[Code Structure],
t1.[Code Site]
from [Vente ] t1
outer apply
(
select distinct top 28 t2.[datecol]
from [Vente ] t2
where t2.[Code Article] = t1.[Code Article]
and t2.[Code Structure]=t1.[Code Structure]
and t2.[Code Site]=t1.[Code Site]
and not exists (SELECT [Code Article]
FROM [Promotion ]
where t2.datecol between
[Date Debut Promo] and [Date Fin Promo]and t2.[Code Article] = [Code Article] )
order by t2.[datecol] desc
) t2
where not exists (SELECT t1.[Code Article]
FROM [Promotion ]
where t1.datecol between
[Date Debut Promo] and [Date Fin Promo]and t1.[Code Article] = [Code Article] )
and (t1.[Code Article] is not null)
and (t1.[Code Structure] is not null)
and (t1.[Prix de Revient] is not null )
and t1.datecol = t2.datecol
and t1.[Code Article] in( select [Code Article] from [Reference] t )
group by t1.[Code Article],
t1.[Code Structure],
t1.[Code Site]
The query took hours executed HOW TO OPTIMIZE it?