簡體   English   中英

連接兩個表並將列值相加

[英]Joining two tables and adding column values together

我有兩個表,在兩個表中都有一個名為phone_number的唯一列,然后有一個名為spring的列以及其他3個列。 彈簧列具有數字值。 該表大約有3000行。 我有一個重復的表,具有相同的信息,但只有大約300行。 我想根據phone_number唯一列合並兩個表的spring列的值。

我曾嘗試過進行MERGE和UNION,但是我不太了解它們如何工作並不斷出現語法錯誤。

SELECT
    accountstwo.phone_number, accountstwo.deposit_total, accountstwo.summer, accountstwo.total_remain,
    (
        SUM(accountstwo.spring) + SUM(accountstwonu.spring)
    ) spring
FROM accountstwo LEFT JOIN
     accountstwonu
     ON accountstwonu.phone_number = accountstwo.phone_number
GROUP BY phone_number;

我可以將表連接起來,但是它將創建一個名為spring的新列,其中只有組合的列總計,而原始表的其他2700行返回為NULL。 我想保留2700行數據以及合並其他300行數據。

這是你想要的嗎?

SELECT a2.phone_number, a2.deposit_total, a2.summer, a2.total_remain,
       (COALESCE(a2.spring, 0) + COALESCE(SUM(a2nu.spring), 0)) as spring
FROM accountstwo a2 LEFT JOIN
     accountstwonu a2nu
     ON a2.phone_number = a2nu.phone_number
GROUP BY a2.phone_number, a2.deposit_total, a2.summer, a2.total_remain, a2.spring;

在兩個表中,我都有一個標題為phone_number的唯一列

如果phone_number在兩個表中都是唯一的,則GROUP BYSUM()沒有意義,因為(LEFT)JOIN結果每個電話號碼只能包含一行。 您所需COALESCE()可能只是為正確的表創建COALESCE() ,以將NULL轉換為零:

SELECT
    accountstwo.phone_number,
    accountstwo.deposit_total,
    accountstwo.summer, accountstwo.total_remain,
    accountstwo.spring + COALESCE(accountstwonu.spring, 0) as spring
FROM accountstwo LEFT JOIN
     accountstwonu
     ON accountstwonu.phone_number = accountstwo.phone_number;

暫無
暫無

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

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