简体   繁体   English

来自多个表的sql总和数据以及来自两个表的条​​目

[英]sql sum data from multiple tables with entries from both tables

I have 2 tables tbl1 and tbl2 where both have the columns [PartID] and [Amount] and [Date]. 我有2个表tbl1和tbl2,它们都具有[PartID]和[Amount]和[Date]列。

I want a query to return something like this : 我想查询返回这样的事情:

PartID | Date | SUM_tbl1 | SUM_tbl2

PartID 1 maybe in tbl1 but not in tbl2 and vice versa and each PART ID has multiple rows in both tables. PartID 1可能在tbl1中,而在tbl2中则不是,反之亦然,并且每个PART ID在两个表中都有多行。

I want both SUM columns to show SUM of each Part IDs in that table. 我希望两个SUM列都显示该表中每个部件ID的总和。 And I want to see SUM as of 6/30/2017. 我希望看到截至6/30/2017的SUM。

Please help! 请帮忙! and thanks! 谢谢!

The simplest? 最简单的? First, use a UNION to assemble a single table with the raw rows you'd need: 首先,使用UNION将单个表与所需的原始行组合在一起:

select PartID, Date, Amt as Table1Entry, NULL as Table2Entry from tbl1
UNION ALL
select PartID, Date, NULL as Table1Entry, Amt as Table2Entry from tbl2

... next, now that you've got both tables's data together, just sum from that as a subquery: ...接下来,既然您已经将两个表的数据都存储在一起,则可以将其作为子查询求和:

select PartID, Date, Sum(Table1Entry) as SumTable1, Sum(Table2Entry) as SumTable2
from
(
    select PartID, Date, Amt as Table1Entry, NULL as Table2Entry from tbl1
    UNION ALL
    select PartID, Date, NULL as Table1Entry, Amt as Table2Entry from tbl2
) mySubquery
GROUP BY PartID, Date

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

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