'Sql optimization query with join on Presto

I have the following query which shows out of all the clicks on products how many no of products have >1 image. The queries separately work fine but when combined its not able to execute within 3m threshold time. Any inputs how can this be optimized best.

select DATE (DATE_TRUNC('week',dt)) AS wk_dt,COUNT(DISTINCT a.product_id) tot_prods,COUNT(DISTINCT b.product_id) multiimp_prods,count(a.product_id) AS total_clicks,count(case when b.product_id>0 then a.product_id END) AS total_mulimg_clicks
    from (
        select product_id,DATE(from_unixtime((time/1000)+19800)) as dt--,count(distinct_id) clicks
        from silver.mixpanel_android__product_clicked
        WHERE DATE(from_unixtime((time/1000)+19800)) BETWEEN date(date_trunc('week',cast(Current_date - interval '14' day AS date))) AND  Current_date
        GROUP BY 1,2) a --2,471,245 1,458,476
    LEFT join (
    SELECT product_id,tot_img
    FROM (SELECT DISTINCT  product_id, catalog_id,(a + b + c + d + e) AS tot_img 
    FROM (
    SELECT product_id,catalog_id,
                   CASE WHEN images is NULL then 0 else 1 end as a,
                   CASE WHEN img_2 is NULL then 0 else 1 end as b,
                   CASE WHEN img_3 is NULL then 0 else 1 end as c,
                   CASE WHEN img_4 is NULL then 0 else 1 end as d,
                   CASE WHEN img_5 is NULL then 0 else 1 end as e
    FROM (
        SELECT DISTINCT id AS  product_id,catalog_id,
                         TRIM(images) AS images,
                         TRIM(SPLIT_PART(images,',',2)) AS "img_2",
                         TRIM(SPLIT_PART(images,',',3)) AS "img_3",
                         TRIM(SPLIT_PART(images,',',4)) AS "img_4",
                         TRIM(SPLIT_PART(images,',',5)) AS "img_5"
        FROM silver.supply__products --WHERE date(created) <= date(date_trunc('week',cast(Current_date - interval '14' day AS date)))
        ) 
                        --GROUP BY 1,2
                        order by 6 asc
            )
            )
            WHERE tot_img>1
        ) b
    on a.product_id=b.product_id
    GROUP BY 1


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source