日期:2014-05-17  浏览次数:21227 次

两个表关联后重复的记录如何只显示一条?
有两个表结构如下:

表a
id       name         address       ....
001     apple1     test1
002     bill2       test2

表b
id       payment       ...
001     20
001     30
002     40
002     50

我现在的sql是这样的:

select   a.id,   a.name,   a.address,   b.payment   from   a,   b   where   a.id   =   b.id;

这样找出来的记录同一个id有多条记录,我现在想一个id只显示一条记录,同一个id有多个payment的话只取第一个,也就是如下结果

id       name       address       payment
001     apple1   test1           20
002     bill2     test2           40

请问这样的sql该怎样写?谢谢.

------解决方案--------------------
select a.id, a.name, a.address, c.pay
from a, (select distinct id, first_value(payment) over(partition by id) pay from b) c where a.id = c.id;
------解决方案--------------------

------解决方案--------------------
一楼正解。

不过可以直接在内联中使用分析函数,看起来简单些,一样的效果:

select a.id, a.name, a.address, first_value(b.payment) over (partition by a.id) payment
from a, b
where a.id = b.id;