Home > OS >  sql for Group By and SUM with date range condition
sql for Group By and SUM with date range condition

Time:11-11

Below is the Invoices table:

enter image description here

I am trying to make a sql query which gives me output based on due_date range with the sum of balance_amount group by company_id

enter image description here

My try:

select invoices.company_id,
SUM(invoices_cmonth.balance_amount) as cmonth,
SUM(invoices_1month.balance_amount) as 1month,
SUM(invoices_2month.balance_amount) as 2month
from `invoices` 
LEFT JOIN invoices invoices_cmonth 
ON (invoices.company_id = invoices_cmonth.company_id and invoices_cmonth.due_date >= '2021-11-10') 
LEFT JOIN invoices invoices_1month 
ON (invoices.company_id = invoices_1month.company_id and invoices_1month.due_date < '2021-11-10' and invoices_1month.due_date >= '2021-10-10')
LEFT JOIN invoices invoices_2month 
ON (invoices.company_id = invoices_2month.company_id and invoices_2month.due_date < '2021-10-10' and invoices_2month.due_date >= '2021-9-10')
where invoices.`status` = 'ACTIVE' 
and invoices.`balance_amount` > 0 
and `invoices`.`deleted_at` is null 
group by invoices.`company_id`

But it is giving me wrong figures in balance amount.

CodePudding user response:

I suggest just making a single pass over the invoices table using conditional aggregation for the various time windows:

SELECT
    company_id,
    SUM(CASE WHEN due_date >= '2021-11-10' THEN balance_amount ELSE 0 END) AS cmonth,
    SUM(CASE WHEN due_date >= '2021-10-10' AND due_date < '2021-11-10'
             THEN balance_amount ELSE 0 END) AS 1month,
    SUM(CASE WHEN due_date >= '2021-09-10' AND due_date < '2021-10-10'
             THEN balance_amount ELSE 0 END) AS 2month
FROM invoices
WHERE
    status = 'ACTIVE' AND balance_amount > 0 AND deleted_at IS NULL
GROUP BY
    company_id;
  • Related