mysqlgocontrollermariadbbeego

How to select sum of specific id in select query MySQL, Beego


I want to get a result like

result 
-------------------------------------------------------
id | uuid | user_id |created_date |    amount    | name 
-------------------------------------------------------
1  | ABC  |    1    |   2019/5/1  |      5       | xa
2  | PQR  |    2    |   2019/5/5  |      150     | xb

A query that I trying to use

SELECT(SELECT SUM(paid_amount) WHERE ID = t1.**HERE**) AS sub1,
(t1.amount - sub1) AS sub2
FROM invoice t1 CROSS JOIN
invoice_paid t2;

Table struct in my DB

table invoice_paid        
------------------------------------
id | uuid | paid_date | paid_amount
------------------------------------
1  | ABC  | 2019/5/1  | 15
2  | ABC  | 2019/5/5  | 80 

table invoice
-------------------------------------------------------
id | uuid | user_id |created_date |    amount    | name 
-------------------------------------------------------
1  | ABC  |    1    |   2019/5/1  |      100     | xa
2  | PQR  |    2    |   2019/5/5  |      150     | xb

I can use sum only 1 condition like where id = 1 but how do I combine this query in select query with a join query. I use beego(golang), MariaDB


Solution

  • You can use this query. It JOINs the invoice table to a derived table of SUMs of all the amounts paid per invoice from invoice_paid, subtracting that total from the invoice amount to get the outstanding amount:

    SELECT i.id, i.uuid, i.user_id, i.created_date, i.amount - COALESCE(p.amount, 0) AS amount, i.name
    FROM invoice i
    LEFT JOIN (SELECT uuid, SUM(paid_amount) AS amount
               FROM invoice_paid
               GROUP BY uuid) p ON p.uuid = i.uuid
    ORDER BY i.id
    

    Output:

    id  uuid    user_id created_date        name    amount
    1   ABC     1       2019-05-01 00:00:00 xa      5
    2   PQR     2       2019-05-05 00:00:00 xb      150
    

    Demo on dbfiddle