[英]MySql: Sum of two columns from two different tables
這可能是重復問題 ,但是我的問題沒有解決。
我正在嘗試使用日期確定物品的內向和外向
表。
A
我將擁有三列,即A_Dt
, A_Na
, A_Qty
B_Dt
, B_N
a, B_Qty
C_Dt
, C_N
a, C_Qty
表示例:
C_Dt C_Na C_Qty
2016-08-01 XY 150
2016-08-03 XY 100
2016-08-04 XY 200
表B:
Date Inward Outward
2016-08-01 200 150
2016-08-02 100 0
2016-08-03 100 100
2016-08-04 200 200
2016-08-05 150 0
表C:
C_Dt C_Na C_Qty 2016-08-01 XY 150 2016-08-03 XY 100 2016-08-04 XY 200
預期產量
Date Inward Outward 2016-08-01 200 150 2016-08-02 100 0 2016-08-03 100 100 2016-08-04 200 200 2016-08-05 150 0
好吧,在這種情況下,我應該使用左連接,否則必須執行以下查詢。
查詢:
select t.Dt as Date, sum(t.Qty) as Inward,sum(t.outward) as outward1 from( select A_Dt as Dt, A_Na as Na, A_Qty as Qty from a union all select B_Dt as Dt, B_Na as Na, B_Qty as Qty from b union all select C_Dt as Dt, C_Na as Na, C_Qty as outward from c )t group by t.Dt, t.Na order by t.Dt;
跟隨錯誤:
#1054 - Unknown column 't.outward' in 'field list'
任何想法都會很棒。
首先使用union all
將兩個表數據合並為一個,然后找到按日期和Na列分組的數量總和。
詢問
select t.Dt, t.Na as Inward, sum(t.Qty) as Outward from(
select A_Dt as Dt, A_Na as Na, A_Qty as Qty from Table_A
union all
select B_Dt as Dt, B_Na as Na, B_Qty as Qty from Table_B
)t
group by t.Dt, t.Na
order by t.Dt;
編輯
實際上,實際上現在不需要合並TableC的數據,但是您必須使用聯接。
詢問
select t1.Dt, t1.Qty as Inward, coalesce(t2.C_Qty, 0) as Outward from(
select t.Dt, t.Na, sum(t.Qty) as Qty from(
select A_Dt as Dt, A_Na as Na, A_Qty as Qty from Table_A
union all
select B_Dt as Dt, B_Na as Na, B_Qty as Qty from Table_B
)t
group by t.Dt, t.Na
)t1
left join Table_C t2
on t1.Dt = t2.C_Dt
order by 1;
結果
+============+========+=========+
| Dt | Inward | Outward |
+------------+--------+---------+
| 2016-08-01 | 200 | 150 |
| 2016-08-02 | 100 | 0 |
| 2016-08-03 | 100 | 100 |
| 2016-08-04 | 200 | 200 |
| 2016-08-05 | 150 | 0 |
+============+========+=========+
您的查詢只需要稍作更正
select t.Dt as Date, sum(t.Qty) as Inward, sum(t.outward) as outward1 from(
select A_Dt as Dt, A_Na as Na, A_Qty as Qty, 0 as outward from a
union all
select B_Dt as Dt, B_Na as Na, B_Qty as Qty, 0 as outward from b
union all
select C_Dt as Dt, C_Na as Na, 0 as Qty, C_Qty as outward from c
)t
-- where Na = 'XY'
group by t.Dt, t.Na
order by t.Dt;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.