简体   繁体   中英

Is it possible to add JOIN query with SUM and GROUP BY in SQL for the following query?

I can read "cust_id" and their dues with the following query in one table called 'incomes' but I have names and address in other table called customer - what I need to add with the query - is it possible to add JOIN query with the following? how?

SELECT cust_id, SUM(inc_text)- (SUM(inc_amount)-  
       SUM(
           case
               when inctype_id =11 then 0
               else inc_amount
           end
       )) Total_due_left  FROM incomes 
                                
  GROUP BY cust_id;

This should work:

SELECT c.*,
       ( SUM(i.inc_text) - (SUM(i.inc_amount) - SUM(CASE WHEN i.inctype_id = 11 then 0 ELSE inc_amount END))
       ) as Total_due_left
FROM incomes i JOIN
     customers c
     ON c.cust_id = i.cust_id                             
GROUP BY c.cust_id;

This works assuming that customers.cust_id is the primary key (or at least declared unique ) in customers . Otherwise you need to list the columns explicitly in the SELECT and GROUP BY .

It also looks like this can be simplified to:

SELECT c.*,
       ( SUM(i.inc_text) - SUM(CASE WHEN i.inctype_id = 11 THEN inc_amount ELSE 0 END)
       ) as Total_due_left
FROM incomes i JOIN
     customers c
     ON c.cust_id = i.cust_id                             
GROUP BY c.cust_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM