要求:我想显示特定B_Name的股票,如果日期相同则会显示在同一行上,如果日期不相同则会显示在不同的行上,并且“ - ”将指定
两张表格gr和frosted
table gr:
B_Name B_Date B_Qty
A 2015-08-11 15000
A 2015-08-15 25000
A 2015-08-31 20000
表格结霜:
M_Name M_Date M_Qty
A 2015-08-11 15000
A 2015-08-25 25000
B 2015-08-20 20000
A 2015-08-15 15000
关注输出:
for Particular B_Name like here (A)
Date Inward(B_Qty) Outward(M_Qty)
2015-08-11 15000 15000
2015-08-15 25000 15000
2015-08-31 20000 -
2015-08-25 - 25000
我尝试了加入和联盟,但它没有按照我的要求工作。
答案 0 :(得分:1)
您希望表gr中的记录在表格中没有匹配,反之亦然。所以你需要一个完整的外连接,MySQL不支持。
一种可能的解决方法:首先使用联合查询获取所有日期,然后再次将表连接外部。
select
alldates.value as "Date",
coalesce(g.b_qty, '-') as "Inward(B_Qty)",
coalesce(f.m_qty, '-') as "Outward(B_Qty)"
from
(
select b_date as value from gr
where b_name = 'A'
union
select m_date from frosted
where m_name = 'A'
) all_dates
left join gr g on g.b_date = all_dates.value
and g.b_name = 'A'
left join frosted f on f.m_date = all_dates.value
and f.m_name = 'A'
答案 1 :(得分:0)
我试过并找到了所需的结果:
SELECT table1.bdate as "Date",coalesce(t1.B_Qty,'-') as "Inward(B_Qty)",coalesce(t2.M_Qty,'-') as "Outward(M_Qty)" FROM ( select B_date as bdate,B_Name as bname from gr union select M_Date as mdate,M_Name as mname from frosted) as table1 LEFT JOIN gr as t1 ON t1.B_Date = table1.bdate LEFT JOIN frosted as t2 ON t2.M_Date = table1.bdate WHERE table1.bname like 'A'