select[top n]中关于查询纪录条数n的问题。可否为变量?

baximu 2003-05-08 03:06:02
表里面有一个字段year_month 纪录数据写入时间
要求只保留12个月的,
思路:从里面取出year_month纪录的个数count
按照升序排列,取出前(count-12)个。
可是再写存储过城时始终不通过,是不是TOP后面不能带一个变量啊?
如果不能哪位更好的办法?
declare @nCountMonth int//总共记录个数
declare @nTempCount int//去掉12个月还剩下的个数
select @nCountMonth = count(distinct year_month) from month
if @nCountMonth > 12
begin
select @nTempCount = @nCountMonth -12
end
select distinct top @nTempCount year_month from MONTH //有问题??
order by year_month ASC
...全文
47 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
blactte 2003-05-08
  • 打赏
  • 举报
回复
保留12个月的与保留前12条记录好象不一样吧
如果保留前12记录用yoki(小马哥) 的方法
如果要求保留12个月内的数据
使用select * from from month
where datediff(month,year_month,getdate())<12
保留12月以内的数据
CrazyFor 2003-05-08
  • 打赏
  • 举报
回复

declare @nCountMonth int//总共记录个数
declare @nTempCount int//去掉12个月还剩下的个数
select @nCountMonth = count(distinct year_month) from month
if @nCountMonth > 12
begin
select @nTempCount = @nCountMonth -12
end
exec('select distinct top '+cast(@nTempCount as varchar)+' year_month from MONTH order by year_month ASC')
happydreamer 2003-05-08
  • 打赏
  • 举报
回复
exec('select distinct top '+ @nTempCount +' year_month from MONTH
order by year_month ASC')
用动态sql做
superzuoluo 2003-05-08
  • 打赏
  • 举报
回复
declare @sql varchar(200)

set @sql = 'select distinct top ' + @nTempCount + ' year_month from MONTH order by year_month ASC'
EXEC(@sql)
yoki 2003-05-08
  • 打赏
  • 举报
回复
exec('select distinct top '+ @nTempCount +' year_month from MONTH
order by year_month ASC')

34,591

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧