Getting the sum of several columns from two tables - sql

I want to get the sum of several columns from 2 different tables (these tables share the same structure).
If I only consider one table, I would write this kind of query:
SELECT MONTH_REF, SUM(amount1), SUM(amount2)
FROM T_FOO
WHERE seller = XXX
GROUP BY MONTH_REF;
However, I would like to also work with the data from the table T_BAR, and then have a select query that return the following columns:
MONTH_REF
SUM(T_FOO.amount1) + SUM(T_BAR.amount1)
SUM(T_FOO.amount2) + SUM(T_BAR.amount2)
everything grouped by the value of MONTH_REF.
Note that a record for a given MONTH_REF can be found in one table but not in the other table.
In this case, I would like to get the sum of T_FOO.amount1 + 0 (or 0 + T_BAR.amount1).
How can I write my SQL query to get this information?
For information, my database is Oracle 10g.

You can union your tables before the group by (this is on Oracle, by the way):
SELECT t.month_ref, SUM(t.amount1), SUM(t.amount2)
FROM (SELECT month_ref, amount1, amount2
FROM T_FOO
WHERE seller = XXX
UNION ALL
SELECT month_ref, amount1, amount2
FROM T_BAR
WHERE seller = XXX
) t
GROUP BY t.month_ref
You may also union the tables with the seller field and filter by it later (in case you need more advanced logic):
SELECT t.month_ref, SUM(t.amount1), SUM(t.amount2)
FROM (SELECT month_ref, amount1, amount2, seller
FROM T_FOO
UNION ALL
SELECT month_ref, amount1, amount2, seller
FROM T_BAR) t
where t.seller = XXX
GROUP BY t.month_ref

Have you tried using a union?
SELECT MONTH_REF, SUM(amount1), SUM(amount2)
FROM (
SELECT MONTH_REF, SUM(amount1) AS amount1, SUM(amount2) as amount2
FROM T_FOO
WHERE seller = XXX
GROUP BY MONTH_REF
UNION ALL SELECT MONTH_REF, SUM(amount1), SUM(amount2)
FROM T_BAR
WHERE seller = XXX
GROUP BY MONTH_REF
) tmp
GROUP BY MONTH_REF

Alternatively, an outer join should also work:
SELECT month_ref,
SUM(t_foo.amount1) + SUM(t_bar.amount1),
SUM(t_foo.amount2)+SUM(t_bar.amount2)
FROM t_foo FULL OUTER JOIN t_bar
ON t_foo.month_ref = t_bar.month_ref
GROUP BY month_ref

I finally get this working using the Lieven's answer.
Here is the correct code (amount1 = ... is not working on my environment, and there are too many ; in the query):
SELECT MONTH_REF, SUM(sumAmount1), SUM(sumAmount2)
FROM (
SELECT MONTH_REF, SUM(amount1) as sumAmount1, SUM(amount2) as sumAmount1
FROM T_FOO
WHERE seller = XXX
GROUP BY MONTH_REF
UNION ALL SELECT MONTH_REF, SUM(amount1), SUM(amount2)
FROM T_BAR
WHERE seller = XXX
GROUP BY MONTH_REF
) tmp
GROUP BY MONTH_REF

SELECT (SELECT SUM(amount) from debit) as debitamounts, (SELECT SUM(amount) from credit) as creditamounts

Related

I want to get difference of sum of a column from two tables

I have 2 tables: transactions and transactions_archive. Each of them has fields accountno,drcr(which has values either as C or D) and field amount. I want to get difference of sum of all 'C' in both transactions and transactions_archive and sum of all 'D' in both transactions and transactions_archive.
What query can I use to get this answer.
I tried this unsuccessfully:
select (
select accountno,drcr,sum(amount)as total from
(
select accountno,drcr,amount
from ebank.tbtransactions
where drcr='C'
union all
select accountno,drcr,amount
from ebank.tbtransactions_archive
where drcr='C'
)
)
-
(select accountno,drcr,sum(amount)as total
from (
select accountno,drcr,amount
from ebank.tbtransactions
where drcr='D'
union all
select accountno,drcr,amount
from ebank.tbtransactions_archive
where drcr='D'
)
)
group by accountno,drcr;
If I understand correctly, you want to subtract all the "D"s from the "C"s. Combine the tables using UNION ALL and use conditional aggregation:
select accountno,
sum(case when drcr = 'C' then amount else - amount end)as total
from ((select accountno, drcr, amount
from ebank.tbtransactions
) union all
(select accountno, drcr, amount
from ebank.tbtransactions_archive
)
) t
where drcr in ('D', 'C')
group by accountno;
SELECT top 1 (amount - nextamount) as diff from(
SELECT
amount,LEAD(amount, 1,0) OVER (ORDER BY YEAR(drcr)) AS nextamount FROM(
SELECT drcr, sum(amount) as amount from transactions JOIN transactions_archive on transactions.drcr and transactions_archive.drcr GROUP BY drcr))

Sum the count(*) of between three tables

I want to sum the number of counts between 3 tables. I have added three input fields to give a specific date each time but I am struggling on how to SUM the COUNTS(*)
select count(*)
from db.table1
where call_date = ${var:call_date};
select count(*)
from db.table2
where call_date = ${var:call_date};
select count(*)
from db.table3
where call_date= ${var:call_date};
thanks in advance
You can simply use them as sub-query as follows:
select (select count(*) from db.table1 where call_date = ${var:call_date})
+ (select count(*) from db.table2 where call_date = ${var:call_date})
+ (select count(*) from db.table3 where call_date= ${var:call_date})
as rslt;
UNION ALL the selects. SUM() the result.
select sum(cnt) from
(
select count(*) cnt
from db.table1
where call_date = ${var:call_date}
UNION ALL
select count(*)
from db.table2
where call_date = ${var:call_date}
UNION ALL
select count(*)
from db.table3
where call_date= ${var:call_date}
) dt

DB2 how to sum two column from two different table

Select sum(amt) as totalA from tableA where id>10;
Select sum(amount) as totalB from tableB where people = 'JOSH';
What is the best way if the objective is to have sum(totalA + totalB)?
select sum(total) from
(
select sum(amt) as total from tableA where id>10
union all
select sum(amount) from tableB where people = 'JOSH'
) as q

Cumulative sum across two tables

I have two tables for Bill & Payment. I have show the balance sheet from these two tables.
The Data in the tables are:
tblBill
tblPayment
My current output is:
The query I'm trying to use is:
select Particulars,Date,BillAmount,0'PaidAmount' from tblBill
union
select Particulars,Date,0'BillAmount',PaidAmount from tblPayment
order by Date
However, I need my output in this format:
Is it possible to get the required format?
There you go:
Assuming there is only one transaction in a day....
With Tb1 as
(select Date,Particulars,BillAmount,0'PaidAmount' from tblBill
union
select Date,Particulars,0'BillAmount',PaidAmount from tblPayment
)
SELECT T1.Particulars,T1.[Date],T1.[BillAmount],T1.[PaidAmount],(Sum(T2.BillAmount) - Sum(T2.PaidAmount)) as Balance FROM Tb1 as T1
INNER JOIN
Tb1 as T2
ON T1.[date] >= T2.[date]
Group By T1.Particulars,T1.[Date],T1.[BillAmount],T1.[PaidAmount]
Order by [Date]
In case of more than one transactions in a day....
WITH Tb0 as
( SELECT [Date],Particulars,BillAmount,0'PaidAmount' from tblBill
UNION
SELECT [Date],Particulars,0'BillAmount',PaidAmount from tblPayment
)
, Tb1 as
(
SELECT Date,Particulars,BillAmount,PaidAmount,Row_Number() over (order by [Date] asc) as [OrderId]
FROM
Tb0
)
SELECT T1.Particulars,T1.[Date],T1.[BillAmount],T1.[PaidAmount],(Sum(T2.BillAmount) - Sum(T2.PaidAmount)) as Balance FROM Tb1 as T1
INNER JOIN
Tb1 as T2
ON T1.[OrderId] >= T2.[OrderId]
Group By T1.Particulars,T1.[Date],T1.[BillAmount],T1.[PaidAmount]
Order by [Date]
You will need to JOIN the two tables. First, there must be a link between the two tables (say customerid existing to show which customer is involved).
Then, you can do.
CREATE VIEW vwTransactionHistory as
SELECT customerid, Particulars, [DATE], BillAmount, PaidAmount,
(SELECT SUM(BillAmount) FROM tblBill x WHERE x.customerid=temp1.customerid and x.date<=temp1.date) as bill2date, (SELECT SUM(PaidAmount) FROM tblPayment y WHERE y.customerid = temp1.customerid and y.date<=temp1.date) as Pay2Date
FROM
(
select customerid, Particulars,[Date],BillAmount,0 AS 'PaidAmount' from tblBill
union
select customerid,Particulars,[Date],0 AS 'BillAmount',PaidAmount from tblPayment
) AS temp1
GROUP BY customerid, Particulars,[Date],BillAmount,PaidAmount
Then you can do
SELECT TOP 1000 [customerid]
,[Particulars]
,[DATE]
,[BillAmount],[PaidAmount], isnull(bill2date,0) - isnull(pay2date,0) as Balance
FROM [vwTransactionHistory]
Remember that you don't need to create a View. I use views for clarity and abstraction of complex Queries.
Check this query
select * from
(
select Particulars,Date,BillAmount,0'PaidAmount' , BillAmount as Balance from tblBill
union
select Particulars,Date,0'BillAmount',PaidAmount, BillAmount - PaidAmount as Balance
from tblPayment p
inner join tblBill b where p.Particulars = p.Particulars
) a
order by Date
You can use this query
SELECT Particulars,Date,BillAmount,PaidAmount,BillAmount-PaidAmount as Balance
FROM(
select Particulars,Date,BillAmount,0'PaidAmount' from tblBill
union
select Particulars,Date,0'BillAmount',PaidAmount from tblPayment
order by Date
)
ORDER BY Date;

A simple way to sum a result from UNION in MySQL

I have a union of three tables (t1, t2, t3).
Each rerun exactly the same number of records, first column is id, second amount:
1 10
2 20
3 20
1 30
2 30
3 10
1 20
2 40
3 50
Is there a simple way in SQL to sum it up, i.e. to only get:
1 60
2 80
3 80
select id, sum(amount) from (
select id,amount from table_1 union all
select id,amount from table_2 union all
select id,amount from table_3
) x group by id
SELECT id, SUM(amount) FROM
(
SELECT id, SUM(amount) AS `amount` FROM t1 GROUP BY id
UNION ALL
SELECT id, SUM(amount) AS `amount` FROM t2 GROUP BY id
) `x`
GROUP BY `id`
I groupped each table and unioned because i think it might be faster, but you should try both solutions.
Subquery:
SELECT id, SUM(amount)
FROM ( SELECT * FROM t1
UNION ALL SELECT * FROM t2
UNION ALL SELECT * FROM t3
)
GROUP BY id
Not sure if MySQL uses common table expression but I would do this in postgres:
WITH total AS(
SELECT id,amount AS amount FROM table_1 UNION ALL
SELECT id,amount AS amount FROM table_2 UNION ALL
SELECT id,amount AS amount FROM table_3
)
SELECT id, sum(amount)
FROM total
I think that should do the trick as well.
As it's not very clear from previous answers, remember to give aliases (on MySQL/MariaDb) or you'll get error:
Every derived table must have its own alias
select id, sum(amount) from (
select id,amount from table_1 union all
select id,amount from table_2 union all
select id,amount from table_3
) AS 'aliasWhichIsNeeded'
group by id
Yes!!! Its okay! Thanks!!!!
My code finishing:
SELECT SUM(total)
FROM (
(SELECT 1 as id, SUM(e.valor) AS total FROM entrada AS e)
UNION
(SELECT 1 as id, SUM(d.valor) AS total FROM despesa AS d)
UNION
(SELECT 1 as id, SUM(r.valor) AS total FROM recibo AS r WHERE r.status = 'Pago')
) x group by id
SELECT BANKEMPNAME, workStation, SUM (CALCULATEDAMOUNT) FROM(
SELECT BANKEMPNAME, workStation, SUM(CALCULATEDAMOUNT) AS CALCULATEDAMOUNT,SALARYMONTH
FROM dbo.vw_salaryStatement
WHERE (ITEMCODE LIKE 'A%')
GROUP BY BANKEMPNAME,workStation, SALARYMONTH
union all
SELECT BANKEMPNAME, workStation, SUM(CALCULATEDAMOUNT) AS CALCULATEDAMOUNT,SALARYMONTH
FROM dbo.vw_salaryStatement
WHERE (ITEMCODE NOT LIKE 'A%')
GROUP BY BANKEMPNAME, workStation, SALARYMONTH) as t1
WHERE SALARYMONTH BETWEEN '20220101' AND '20220131'
group by BANKEMPNAME, workStation
order by BANKEMPNAME asc
IN MSSQL You can write this way, But Doing UNION ALL THE Column should be the same for both ways.
I have given this example So that you can understand the process...