是否可以在sql中为以下查询添加sum和group by连接查询?

gojuced7  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(242)

我可以在一个名为“incomers”的表中用下面的查询读取“cust\u id”及其应付款项,但在另一个名为customer的表中有名称和地址-我需要用查询添加什么-是否可以用下面的查询添加join查询?怎样?

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;
oaxa6hgo

oaxa6hgo1#

这应该起作用:

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;

这是在假设 customers.cust_id 是主键(或至少声明 unique )在 customers . 否则,需要在 SELECT 以及 GROUP BY .
这看起来也可以简化为:

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;

相关问题