Daniel
Daniel

Reputation: 6765

Aggregate SQL query on tables with column with same name

I have two tables, both with a column called transaction_amnt. Is there a way I can write a SQL query that returns the sum of all of the transaction amounts in both tables? I tried

select sum(transaction_amnt) from table1 natural join table2;

but, I'm thinking that join isn't really what I want here.

Upvotes: 0

Views: 455

Answers (2)

user330315
user330315

Reputation:

As you did not show us your table definition it is not clear to me what you really want, but this might what I think you are looking for:

select sum(transaction_amnt) 
from (
  select transaction_amnt
  from table1 
  union 
  select transaction_amnt
  from table2
) t

Upvotes: 0

John Woo
John Woo

Reputation: 263803

I guess union all best fits to your question as it will not remove duplicates on the records.

SELECT SUM(x.transaction_amnt) totalAmount
FROM
(
    SELECT transaction_amnt from table1
    UNION ALL
    SELECT transaction_amnt from table2
) x

Upvotes: 1

Related Questions