inner join 重复记录如何处理。
这是现在用inner join连接两个表查询出来的数据:
bh xm gz cl gzz
123 丽丽 118.5 95 a
123 丽丽 118.5 95 b
123 丽丽 118.5 95 c
456 峰 3004.8 1548 a
456 峰 3004.8 1548 b
456 峰 3004.8 1548 c
456 峰 3004.8 1548 d
这是表a:
bh xm gzz
123 丽丽 a
123 丽丽 b
123 丽丽 c
456 峰 a
456 峰 b
456 峰 c
456 峰 d
这是表b
bh xm gz cl
123 丽丽 118.5 95
456 峰 3004.8 1548
我现在想要这样的结果:
bh xm gz cl gzz
123 丽丽 118.5 95 a
123 丽丽 b
123 丽丽 c
456 峰 3004.8 1548 a
456 峰 b
456 峰 c
456 峰 d
不知道怎么实现,谢谢指教!
------解决方案--------------------select a.bh,a.xm,(case when a.gzz= 'a ' then b.gz else ' ' end ) as gz, (case when a.gzz= 'a ' then b.cl else ' ' end ) as cl,a.gzz
from a inner join b
on a.bh=b.bh
------解决方案--------------------如果gzz列不固定。可以这样
select a.bh,a.xm,(case when not exists (select 1 from a c where a.gzz> c.gzz) then b.gz else ' ' end ) as gz, (case when not exists (select 1 from a c where a.gzz> c.gzz) then b.cl else ' ' end ) as cl,a.gzz
from a inner join b
on a.bh=b.bh
------解决方案--------------------select b.*,a1.gzz from a a1,b
where a1.bh=b.bh
and not exists (select 1 from a
where bh=a1.bh and gzz <a1.gzz
)
union all
select bh,xm,null as gz,null as cl,gzz
from a a2
and exists (select 1 from a
where bh=a2.bh and gzz <a2.gzz
)