我有一张桌子
主表:tblMain
Phase Country City
AAA India Bangalore
AAA USA Chicago
ZZZ USA
ZZZ UK
SubTable:tblSub
Phase Country City Value
AAA USA Chicago 3
AAA USA NY 6
AAA UK London 5
AAA India Bangalore 6
AAA India Delhi 9
ZZZ USA Chicago 7
ZZZ UK London 8
预期结果
Phase Country City Value
AAA India Bangalore 6
AAA USA Chicago 3
ZZZ USA 7
ZZZ UK 8
我想加入我的Main表,其中包含Phase,Country和City,但条件是 对于Phase" ZZZ"我想只在国家和地区进行加入,而#34; AAA"我想加入ty Country&市。可以在没有存储过程或临时表的情况下在SQL查询中执行 我希望在简单的查询中实现这一点。在此先感谢!!!
答案 0 :(得分:1)
SELECT *
FROM This_Table TT
LEFT JOIN Main_Table MT ON TT.Countrry = MT.Country
AND TT.Phase = 'ZZZ'
LEFT JOIN Main_Table MT2 ON TT.Countrry = MT2.Country
AND TT.City = MT2.City
AND TT.Phase = 'AAA'
答案 1 :(得分:1)
这应该这样做:
WHERE
(a.phase = 'ZZZ' AND a.country = b.country)
OR
(a.phase = 'AAA' AND a.country = b.country AND a.city = b.city)