Sql Query to Sum Fields from Different Tables

SQL: How to to SUM two values from different tables

select region,sum(number) total
from
(
select region,number
from cash_table
union all
select region,number
from cheque_table
) t
group by region

How to sum two columns of different tables in sql

In case not all books had a CD:

SELECT A.Books
, A.Book_ID
, A.Author
, B.CD_Name
, A.rate+COALESCE(B.Cd_price,0) AS TOTAL_PRICE
FROM BOOK A
LEFT JOIN CD B ON A.BOOK_ID = B.BOOK_ID

Question's author evidenced that "The table name is book not Books"

I used originally BOOKS as a "suggestion" because (usually) tables name are plural.

SQL Query to sum fields from different tables

Or you can take advantage of using SubQueries:

select A.ID, A.Total, b.SB as AmountB, c.SC as AmountC, d.SD as AmountD
from A
inner join (select ExtID, sum(Amount) as SB from B group by ExtID) b on A.ID = b.ExtID
inner join (select ExtID, sum(Amount) as SC from C group by ExtID) c on c.ExtID = A.ID
inner join (select ExtID, sum(Amount) as SD from D group by ExtID) d on d.ExtID = A.ID

sql - getting sum of same column from multiple tables

You can achieve it using Coalesce as follows

SELECT 
(SELECT coalesce(SUM(value),0) FROM table1) +
(SELECT coalesce(SUM(value),0) FROM table2) +
(SELECT coalesce(SUM(value),0) FROM table3) as total_sum

Another approach is to use union all to merge all values into single table

select distinct coalesce(sum(a.value), 0) as total_sum from
(select value from table1
union all
select value from table 2
union all
select value from table 3) a;

Find sum() from two different tables and join them based on a condition?

You can use union all and group by. For all ids:

select id, date, sum(amount), sum(amount_settled)
from ((select id, date, amount, null as amount_settled
from table1
) union all
(select id, date, null as amount, amount_settled
from table2
)
) t
group by id, date
order by date;

You can filter for a particular id using a where clause in the outer query.

how to sum two columns from different tables MySQL

First use UNION ALL to get all the rows from the 2 tables that you want and then aggregate:

SELECT session_id, SUM(points) AS total_points
FROM (
SELECT session_id, spent_points AS points
FROM session_details
WHERE session_id IN ("-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy")
UNION ALL
SELECT session_id, price_points
FROM template_sales
WHERE session_id IN ("-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy")
) t
GROUP BY session_id

SQL How to use SUM and Group By with multiple tables?

Here is a solution based on your data. Issue with your query is that you were joining tables on a non-unique column resulting in Cartesian product.

Data

DROP TABLE IF EXISTS A;

CREATE TABLE A
(num int,
id int,
col1 int);

INSERT INTO A VALUES (1, 100, 0);
INSERT INTO A VALUES (2, 100, 1);
INSERT INTO A VALUES (3, 100, 0);
INSERT INTO A VALUES (1, 101, 1);
INSERT INTO A VALUES (2, 101, 1);
INSERT INTO A VALUES (3 , 101, 0);

DROP TABLE IF EXISTS B;

CREATE TABLE B
(idx int,
id int,
col2 int);

INSERT INTO B VALUES (1, 100, 20);
INSERT INTO B VALUES (2, 100, 20);
INSERT INTO B VALUES (3, 100, 20);
INSERT INTO B VALUES (4, 101, 100);
INSERT INTO B VALUES (5, 101, 100);

DROP TABLE IF EXISTS C;

CREATE TABLE C
(idx int,
id int,
col3 int);

INSERT INTO C VALUES (1, 100, 1);
INSERT INTO C VALUES (2, 100, 1);
INSERT INTO C VALUES (3, 100, 1);
INSERT INTO C VALUES (4, 101, 10);
INSERT INTO C VALUES (5, 101, 1);

Solution

SELECT a_sum.id, col1_sum, col2_sum, col3_sum
FROM (SELECT id, SUM(col1) AS col1_sum
FROM a
GROUP BY id ) a_sum
JOIN
(SELECT id, SUM(col2) AS col2_sum
FROM b
GROUP BY id ) b_sum
ON (a_sum.id = b_sum.id)
JOIN
(SELECT id, SUM(col3) AS col3_sum
FROM c
GROUP BY id ) c_sum
ON (a_sum.id = c_sum.id);

Result is as expected

Sample Image

Note: Do outer joins if an id doesnt have to be present in all three tables.

Query SUM for two fields in two different tables

You need to use a subquery to aggregate the fees table before the join:

SELECT sum(prijs) as SumOfPrijs, sum(amount) as SumOfFees, sum(prijs)+sum(amount) AS   
Total, year(vertrekdatum) as year
FROM tbl_vluchtgegevens vg LEFT JOIN
(select f.gegevenId, sum(amount) as Amount
from tbl_fees f
group by f.gegevenId
) f
ON f.gegevenID = vg.gegevenID
WHERE vertrekdatum <=NOW()
GROUP by year(vertrekdatum);

The problem is that the multiple fees on on "gegeven" is causing the join to produce unexpected rows, that affect the sum.

SQL select sum with multiple where from different tables

Original Answer

First off, your submitted SQL was a mess, things were completely out of the conventional order, I'm not sure it would execute as presented. That said, this should do what you want, assuming I understand your desired output correctly:

SELECT users.id, users.name, users.surname, ROUND(SUM(purchases.sum),2) AS totalSum
FROM purchases
LEFT JOIN users ON users.id = purchases.user_id
WHERE status='completed'
GROUP BY users.name, users.surname
ORDER BY users.id

The key aspect you were missing from your query was the GROUP BY section, I added ORDER BY for my own benefit on my fiddle, use it if you wish, or not.

Here's a fiddle I prepped for you prior to your posting of your sample data, the main answer has been given by others I see so I'm just posting this because I already did the work on it. http://sqlfiddle.com/#!9/8fa2d/6/0

Answer 2.0

Fiddle is acting up so this is untested but give it a try.

SELECT users.id, users.name, users.surname, ROUND(SUM(CASE WHEN purchases.status = 'completed' THEN purchases.sum ELSE 0 END),2) AS totalSum 
FROM users
LEFT JOIN purchases ON users.id = purchases.user_id
GROUP BY users.id
ORDER BY users.id


Related Topics



Leave a reply



Submit