簡體   English   中英

是否可以在 SQL 中為以下查詢添加帶有 SUM 和 GROUP BY 的 JOIN 查詢?

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

我可以在一個名為“incomes”的表中使用以下查詢讀取“cust_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;

這應該有效:

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_idcustomers中的主鍵(或至少聲明為unique )的情況下起作用。 否則,您需要在SELECTGROUP 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM