How can i get current day, current week, current month, current year sales sum in single mysql query?

I have written the below query individually, but I want in a single query, how to do this, can anyone help..?

SELECT IFNULL(SUM(net_amount),0) as current_date FROM orders WHERE is_cancelled = false and business_date = CURRENT_DATE();
SELECT IFNULL(SUM(net_amount),0) as current_week FROM orders WHERE is_cancelled = false and YEARWEEK(business_date) = YEARWEEK(CURRENT_DATE());
SELECT IFNULL(SUM(net_amount),0) as current_month FROM orders WHERE is_cancelled = false and MONTH(business_date) = MONTH(CURRENT_DATE());
SELECT IFNULL(SUM(net_amount),0) as current_year FROM orders WHERE is_cancelled = false and YEAR(business_date) = YEAR(CURRENT_DATE());

Answer

You can use conditional aggregation in order to combine all seperate select statement into unified one such as

SELECT SUM(CASE WHEN business_date = CURRENT_DATE() 
                THEN 
                    net_amount 
                ELSE 
                    0 
                 END ) AS current_date,
       SUM(CASE WHEN YEARWEEK(business_date) = YEARWEEK(CURRENT_DATE()) 
                THEN 
                    net_amount 
                ELSE 
                    0 
                 END ) AS current_week,
       SUM(CASE WHEN MONTH(business_date) = MONTH(CURRENT_DATE()) 
                THEN 
                    net_amount 
                ELSE 
                    0 
                 END ) AS current_month,
       SUM(CASE WHEN YEAR(business_date) = YEAR(CURRENT_DATE()) 
                THEN 
                    net_amount 
                ELSE 
                    0 
                 END ) AS current_year       
  FROM orders 
 WHERE is_cancelled = false

Leave a Reply

Your email address will not be published. Required fields are marked *