简体   繁体   English

在具有相同名称的列的表上聚合SQL查询

[英]Aggregate SQL query on tables with column with same name

I have two tables, both with a column called transaction_amnt . 我有两个表,每个表都有一个名为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? 有没有一种方法可以编写一个SQL查询来返回两个表中所有交易金额的总和? I tried 我试过了

select sum(transaction_amnt) from table1 natural join table2;

but, I'm thinking that join isn't really what I want here. 但是,我认为join并不是我真正想要的。

I guess union all best fits to your question as it will not remove duplicates on the records. 我认为union all合并最适合您的问题,因为它不会删除记录中的重复项。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM