I have the following query which contain 2 sub query which retrieve a flag if a row exist by conditions. I am wondering if there is a way to optimize the time it runs. My understanding is that decreasing the number of rows at early stage (sub queries) is optimum. So I add a bunch of where
condition in the sub query. Then, i will keep only those rows where both condition is record exists
. Is there a faster way of doing this?
Note: the only difference between the sub queries is the division_cd
. But I could not merge them by doing a AND
as there are different rows.
SELECT cc_id_hashed
, division_cd
, dpt_code
, sales_area_cd
, YEAR([trade_datetime]) as year_nb
, datepart(week, [trade_datetime]) as week_nb
, SUM(item_unit_price_aftertax * sales_num) as sales
, (
CASE
WHEN EXISTS (
SELECT 1
FROM iy_store_sales as t2
WHERE division_cd = 01
AND is_returned_trade = 0
AND payment_type = 01000
AND company_cd = 001
AND YEAR(t1.[trade_datetime]) = YEAR(t2.[create_date])
AND datepart(week, t1.[trade_datetime]) = datepart(week, t2.[trade_datetime])
GROUP BY cc_id_hashed
,YEAR([trade_datetime])
,datepart(week, [trade_datetime])
)
THEN 'Record Exists'
ELSE 'Record doesn''t Exists'
END
) AS [first_flag]
, (
CASE
WHEN EXISTS (
SELECT 1
FROM iy_store_sales as t2
WHERE division_cd = 03
AND is_returned_trade = 0
AND payment_type = 01000
AND company_cd = 001
AND YEAR(t1.[trade_datetime]) = YEAR(t2.[trade_datetime])
AND datepart(week, t1.[trade_datetime]) = datepart(week, t2.[trade_datetime])
GROUP BY cc_id_hashed
,YEAR([trade_datetime])
,datepart(week, [trade_datetime])
)
THEN 'Record Exists'
ELSE 'Record doesn''t Exists'
END
) AS [second_flag]
FROM iy_store_sales t1
WHERE division_cd in (01,03)
AND is_returned_trade = 0
AND payment_type = 01000
AND company_cd = 001
GROUP by cc_id_hashed, division_cd, dpt_code, sales_area_cd, YEAR([trade_datetime]), datepart(week, [trade_datetime])
ORDER BY YEAR([trade_datetime]), datepart(week, [trade_datetime])