I have the following query with left join can I make this as subquery instead? Will it work faster since it’s the same table? I will only want to get the revenue rows and show revenue2 only for them
SELECT * FROM (SELECT s_campaign_id, SUM(CASE WHEN d_gen_date BETWEEN '2021-01-31' AND '2021-01-31' THEN f_revenue ELSE 0 END) AS revenue, SUM(CASE WHEN d_gen_date BETWEEN '2021-01-30' AND '2021-01-30' THEN f_revenue ELSE 0 END) AS revenue2 FROM tbl_reports WHERE (d_gen_date >= '2021-01-31' AND d_gen_date <= '2021-01-31') GROUP BY s_campaign_id) d1 LEFT JOIN (SELECT s_campaign_id, SUM(CASE WHEN d_gen_date BETWEEN '2021-01-30' AND '2021-01-30' THEN f_revenue ELSE 0 END) AS revenue2 FROM tbl_reports WHERE (d_gen_date BETWEEN '2021-01-30' AND '2021-01-30') GROUP BY s_campaign_id) d2 ON d1.s_campaign_id = d2.s_campaign_id
Advertisement
Answer
Your query is quite suspicious as you can achieve the desired result using minor changes in first query as follows:
SELECT T.* FROM (SELECT s_campaign_id, SUM(CASE WHEN d_gen_date = '2021-01-31' THEN f_revenue ELSE 0 END) AS revenue, SUM(CASE WHEN d_gen_date = '2021-01-30' THEN f_revenue ELSE 0 END) AS revenue2 FROM tbl_reports WHERE (d_gen_date>='2021-01-30' AND d_gen_date<='2021-01-31') GROUP BY s_campaign_id) T WHERE EXISTS (select 1 from tbl_reports tt where t.s_campaign_id = tt.s_campaign_id and tt.d_gen_date ='2021-01-31')