可能是重复的问题,但我的问题不是解决。
我正在尝试使用日期确定项目的内向和外向
表。
A_Dt
。我会有三列
即A_Na
,A_Qty
,B_Dt
B_N
,B_Qty
a,C_Dt
C_N
,C_Qty
a,Table :A
A_Dt A_Na A_Qty
2016-08-01 XY 50
2016-08-02 XY 100
2016-08-05 XY 150
表格示例:
B_Dt B_Na B_Qty
2016-08-01 XY 150
2016-08-03 XY 100
2016-08-04 XY 200
表B:
C_Dt C_Na C_Qty
2016-08-01 XY 150
2016-08-03 XY 100
2016-08-04 XY 200
表C:
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'
以下错误:
{{1}}
任何想法都会很棒。谢谢。
答案 0 :(得分:4)
首先使用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 |
+============+========+=========+
答案 1 :(得分: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;