日期:2014-05-18  浏览次数:20657 次

求一个很绕人的sql语句,高手进哦
hot表:gsid不重复
id       gsid    
1           123
2           234
3           345
4           456  
5           567
xxb表:gsid重复出现
id     gsid     mc         bz
1       123       aaa
2       123       aaa
3       234       bbb
4       345       ccc
5       345       ccc
6       456       ddd  
7       665       eee       1  
8       666       fff
9       667       ggg       1
10     668       hhh       1  
实现:提取5条记录,hot表中每个gsid只取一条最新记录,假如不足5条,则取xxb.bz=1的记录补足5条,总之保持5条记录,优先取hot表中gsid的

------解决方案--------------------
楼主的需求真难猜啊

--执行测试语句
select top 5 id,gsid,mc,bz
from(
select distinct hot.id,xxb.gsid,mc,bz,1 as order_by
from hot
join xxb on xxb.gsid=hot.gsid
union
select top 5 id,gsid,mc,bz ,2 as order_by from xxb where bz = 1
)x
order by order_by,id

go
--删除测试环境
drop table hot,xxb
go
/*--测试结果
id gsid mc bz
----------- ----------- ---------- -----------
1 123 aaa NULL
2 234 bbb NULL
3 345 ccc NULL
4 456 ddd NULL
7 665 eee 1

(5 row(s) affected)
*/