日期:2014-05-18 浏览次数:20624 次
declare @v varchar(1000) select top 5 aa.* into tmp from hot a left join (select * from xxb a where not exists(select 1 from xxb where gsid=a.gsid and date>a.date)) aa on a.gsid=aa.gsid where aa.gsid is not null if @@rowcount<5 begin set @v='insert tmp select top '+ltrim(5-@@rowcount)+' * from xxb where bz=1' exec(@v) end select * from tmp drop table tmp
------解决方案--------------------
1、取出xxb的id,gsid,cpmc,bz,date字段
select * from xxb
2、只取5条记录,按照xxb.date排序,必须保持5条记录
select top 5 * from xxb order by date
3、优先取hot表中gsid的一条记录,也就是一个gsid只取一条记录,且只取改gsid里日期最新的一条 (不一定就是id最大,用户可能修改记录)
select hot.gsid , max(date) date from hot , xxb where hot.gsid = xxb.gsid
如果取所有字段
select a.* from
(
select hot.*,xxb.* from hot.gsid = xxb.gsid
) a,
(
select hot.gsid , max(date) date from hot , xxb where hot.gsid = xxb.gsid
) b
where a.gsid = b.gsid and a.date = b.date
4、假如满足hot表的gsid的记录不够5条,则取xxb.bz=1的记录补足5条
这个没看懂。
------解决方案--------------------
你的表里是不是少一个时间字段
这个是你想要的结果吗?
select top 5 id,gsid,cpmc,bz,date from xxb where gsid=(select gsid from hot a where not exists(select gsid from hot where 日期>a.日期)) or bz=1 group by bz
------解决方案--------------------
[code=SQL][/code]
declare @a table(id int,gsid int)
insert into @a
select 1,123
union all select 2,234
union all select 3,345
declare @b table(id int,gsid int,cpmc varchar(10),bz int,date datetime)
insert into @b
select 1,123,'aaa',0,'2006-1-3'
union all select 2,123,'aaa',0,'2007-5-6'
union all select 3,234,'bbb',0,'2007-3-6'
union all select 4,345,'ccc',0,'2007-5-10'
union all select 5,345,'ccc',0,'2007-8-7'
union all select 6,456,'ddd',0,'2007-5-7'
union all select 7,665,'eee',1,'2007-3-4'
union all select 8,666,'ggg',0,'2007-1-6'
union all select 9,667,'ggg',1,'2007-12-7'
union all select 10,559,'hhh',1,'2007-10-8'
create table #b(id int,gsid int,cpmc varchar(10),bz int,date datetime)
insert into #b
select bb.* from(
select b.gsid,date=max(date) from @a a,@b b where a.gsid=b.gsid group by b.gsid
) aa,@b bb where bb.date=aa.date
declare @c int,@sql nvarchar(1000)
select @sql='select @d=count(*) from #b q '
exec sp_executesql @sql,N'@d int output',@c output
select @c
if @c<5
begin
insert into #b
select b.* from @b b where b.bz=1 order by b.id
select top 5 * from #b
end