请你进来看看这个SQL如何写?先谢了。

Spring414 2003-10-15 01:55:57
有这样的一张表:(ID是自动编号)
ID MainID Name
1 1 a
2 1 b
3 1 c
4 2 d
5 2 e
6 3 f

能不能写出这样的SQL?
给出一个参数@Index
当@Index = 1时,得到:
1 1 a
4 2 d
6 3 f
当@Index = 2时,得到:
2 1 b
5 2 e
6 3 f(不变)
当@Index = 3时,得到:
3 1 c
5 2 d(不变)
6 3 f(不变)
...全文
81 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
Spring414 2003-10-15
  • 打赏
  • 举报
回复
呵,不好意思!!
fllc 2003-10-15
  • 打赏
  • 举报
回复
gz
realgz 2003-10-15
  • 打赏
  • 举报
回复
原来结贴了啊。。。。浪费感情。。。
realgz 2003-10-15
  • 打赏
  • 举报
回复


select
(top 1 id from table t where (select count(*) from table t2 where t2.mainid=t.mainid and t2.id<=t.id)<=@index order by id desc) as id,
mainid,
select (top 1 name from table t where (select count(*) from table t2 where t2.mainid=t.mainid and t2.id<=t.id)<=@index order by id desc) as name
from table
group by mainid
samuelpan 2003-10-15
  • 打赏
  • 举报
回复
这么早就结贴?

继续贡献另外一种方法:

create table test(id int identity(1,1),MainID int,name char(1))
insert test values(1,'a')
insert test values(1,'b')
insert test values(1,'c')
insert test values(2,'d')
insert test values(2,'e')
insert test values(3,'f')

create proc t2 @index int
as
select a.* from test a,(select case When min(id)+@index-1 > max(id) then max(id) else min(id)+@index-1 end id from test group by mainid) b
where a.id=b.id
Spring414 2003-10-15
  • 打赏
  • 举报
回复
谢谢大家!!
Spring414 2003-10-15
  • 打赏
  • 举报
回复
可以了啊,是要降序的,升序就错了。

谢谢 马可!
samuelpan 2003-10-15
  • 打赏
  • 举报
回复
先顺序取后倒序取,是好办法。

cast(@index as varchar(10))

取多少都没关系了。
a1n1 2003-10-15
  • 打赏
  • 举报
回复
to:txlicenhe(马可)
……aa order by id desc)'
对表a 的查询不能以id降序,该为升序
Spring414 2003-10-15
  • 打赏
  • 举报
回复
真厉害啊。我先研究研究。
txlicenhe 2003-10-15
  • 打赏
  • 举报
回复
1: exec t 1
id MainID name
----------- ----------- ----
1 1 a
4 2 d
6 3 f

(所影响的行数为 3 行)
2: exec t 2
id MainID name
----------- ----------- ----
2 1 b
5 2 e
6 3 f

(所影响的行数为 3 行)
3: exec t 3
id MainID name
----------- ----------- ----
3 1 c
5 2 e
6 3 f

(所影响的行数为 3 行)



txlicenhe 2003-10-15
  • 打赏
  • 举报
回复
create table test(id int identity(1,1),MainID int,name char(1))
insert test values(1,'a')
insert test values(1,'b')
insert test values(1,'c')
insert test values(2,'d')
insert test values(2,'e')
insert test values(3,'f')

create procedure t @index int
As
declare @s varchar(1000)
set @s = 'Select * from test a where id = (select top 1 id from (select top ' + cast(@index as varchar(1)) + ' id from test where Mainid =a.MainID order by id ) aa order by id desc) '
exec(@s)

txlicenhe 2003-10-15
  • 打赏
  • 举报
回复
挺难的,试试
zhaoloudy 2003-10-15
  • 打赏
  • 举报
回复
什么意思?

34,576

社区成员

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

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