我是MYSQl的新手,请帮帮我.. 以下查询部分工作正常,但对于某些行,它的值加倍,当两个表在两行或更多行中具有相同的日期时会发生这种情况,例如此处2015-08-11在第一个表中为3,在另一个表中为2。
select all_dates.value1 as "Date",
sum(coalesce(g.Qty1, '-')) as "Inward(B_Qty)",
sum(coalesce(f.Qty2, '-')) as "Outward(B_Qty)"
from
( select distinct Date1 as value1 from inward where Name = 'A' union
select distinct Date2 from outward where Name = 'A'
) as all_dates
left join inward g
on g.Date1 = all_dates.value1 and g.Name = 'A'
left join outward f
on f.Date2 = all_dates.value1 and f.Name = 'A' group by all_dates.value1,f.Date2
table no. 1 :- Inward
Name Qty1 Date1
A 25000 2015-08-11
A 15000 2015-08-12
A 45000 2015-08-11
B 150000 2015-09-11
B 85000 2015-07-08
B 15000 2015-07-08
table no 1:Outward
Name Qty2 Date2
A 15000 2015-08-01
A 25000 2015-08-09
A 15000 2015-08-11
A 45000 2015-08-11
B 25000 2015-07-25
预期的输出
Date Inward Outward
2015-08-11 70000 60000
2015-08-09 - 25000
2015-08-01 - 15000
2015-08-12 15000 -
实际输出:
Date Inward(B_Qty) Outward(B_Qty)
2015-08-01 0 15000
2015-08-09 0 25000
2015-08-11 140000 120000
2015-08-12 15000 0
实际输出的第三行是值的两倍。为什么它发生了不知道。
答案 0 :(得分:0)
尝试这种方式:
select all_dates.value1 as "Date",
sum(coalesce(g.Qty1, '-')) as "Inward(B_Qty)",
sum(coalesce(f.Qty2, '-')) as "Outward(B_Qty)"
from
( select distinct value1 from (Select Date1 as value1 from inward where Name = 'A' union
select Date2 from outward where Name = 'A') as TmpDates
) as all_dates
left join inward g
on g.Date1 = all_dates.value1 and g.Name = 'A'
left join outward f
on f.Date2 = all_dates.value1 and f.Name = 'A' group by all_dates.value1,f.Date2
答案 1 :(得分:0)
尝试加入已经包含每Date1
,Date2
总和的派生表:
select all_dates.value1 as `Date`,
coalesce(`Inward(B_Qty)`, '-') as `Inward(B_Qty)`,
coalesce(`Outward(B_Qty)`, '-') as `Outward(B_Qty)`
from
(
select distinct Date1 as value1 from inward where Name = 'A' union
select distinct Date2 from outward where Name = 'A'
) as all_dates
left join
(
select `Date1`, sum(Qty1) AS `Inward(B_Qty)`
from inward
where Name = 'A'
group by `Date1`
) as g
on g.Date1 = all_dates.value1
left join
(
select `Date2`, sum(Qty2) AS `Outward(B_Qty)`
from outward
where Name = 'A'
group by `Date2`
) as f
on f.Date2 = all_dates.value1
group by all_dates.value1