1

When the query below is used I get 7 records from the database.

SELECT pickup_date::date, 
       SUM(CASE WHEN paid ='Yes' THEN price  ELSE 0  END) AS  TotalMoMoPaid 
from requests 
where order_status = 'Done' 
  and payment_mode = 'MoMo' 
  and pickup_date::date >= current_timestamp::date - INTERVAL '7 days' 
GROUP BY pickup_date::date,paid,order_status,price

enter image description here

When the same query is used as a sub query, I get 2 records which is not what I expect,

SELECT pickup_date::date,
       sub.TotalMoMoPaid, 
       SUM(CASE WHEN order_status ='Done' THEN price  ELSE 0  END) AS "TotalCashSales" 
from (
  SELECT paid as subPaid,
         order_status as subStatus,
         price as subPrice, 
         SUM(CASE WHEN paid ='Yes' THEN price  ELSE 0  END) AS  TotalMoMoPaid 
  from requests 
  where order_status = 'Done' 
    and payment_mode = 'MoMo' 
    and pickup_date::date >= current_timestamp::date - INTERVAL '7 days' 
  GROUP BY pickup_date::date,subPaid,subStatus,subPrice
) AS sub, requests  
where order_status ='Done' 
  and payment_mode = 'Cash' 
  and pickup_date::date >= current_timestamp::date - INTERVAL '7 days'
GROUP BY sub.TotalMoMoPaid,subPaid,pickup_date::date 
ORDER BY sub.TotalMoMoPaid,pickup_date::date

enter image description here

1
  • Never use commas in the FROM clause. Always use proper, explicit, standard, readable JOIN syntax. After all, what would you expect from a Cartesian product other than multiplying the number of rows? Commented Aug 24, 2020 at 10:54

1 Answer 1

1

This query should work instead of using subqueries;

SELECT pickup_date::date,
       SUM(CASE WHEN payment_mode = 'MoMo' and paid = 'Yes' THEN price  ELSE 0  END) AS TotalMoMoPaid,
       SUM(CASE WHEN payment_mode = 'Cash' and paid = 'Yes' THEN price  ELSE 0  END) AS TotalCashSales
FROM requests 
WHERE order_status = 'Done' 
      and pickup_date::date >= current_timestamp::date - INTERVAL '7 days' 
GROUP BY pickup_date::date,paid,order_status,price
Sign up to request clarification or add additional context in comments.

3 Comments

Ok sure but the query is now bring out data of same dates on different rows, it has to sum up for same dates. check the link below ibb.co/qgJsMg5
I think payment mode in group by causes this, so i edited the query. Can you try the new version?
Thanks for your help, it fixed after I removed paid,order_status,price from the GROUP BY

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.