如何只查询查询结果的第二,第三,第四或第五行?(SQL SERVER 2000)

时间:2009-02-11 21:05:11

标签: sql-server-2000

我需要一个建议甚至是一个解决方案,如何只获得具有高性能的查询结果的第二,第三行。我知道有可能是row_number(SQL Server 2005或更高版本)但不适用于SQL Server 2000 :-(

我第一次尝试获得第五行是:
SELECT TOP 1 col
FROM(选择TOP 5 col
                       从表
                       ORDER BY col)q
ORDER BY col DESC

我试着解释我的要求:在我的表中可以有最大值。一个人5行。但是,如果此人只有4行,我将使用上述查询得到错误的结果。

有什么建议吗?

任何帮助将不胜感激!

Thx forward,Best Regards Andreas

5 个答案:

答案 0 :(得分:1)

执行此操作的最佳和最快方法可能只是选择数据加载器中的前5位,然后根据需要将内容读入内存。

答案 1 :(得分:1)

要获得第5行,您可以使用多个子查询,例如:

select top 1 MyCol from MyTable
where MyCol = 
(
    select top 1 MyCol from 
    (
        select top 5 MyCol from MyTable order by MyCol
    ) t order by MyCol desc
)

答案 2 :(得分:0)

如果我理解正确,例如,如果确实存在第5行,则只需要返回行。在这种情况下,您可以这样做:

SELECT TOP 1 col
FROM (
    SELECT TOP 5 col
    FROM table
    where (SELECT COUNT(*) FROM table) >= 5
    ORDER BY col
) q
ORDER BY col DESC

答案 3 :(得分:0)

应该这样做......

CREATE PROCEDURE [dbo].[sp_UpdateSkills]
AS
BEGIN
    set nocount on

    declare @UserID int
    declare @Skill varchar(1)
    declare @SkillCount int

    declare @Skill1 varchar(1)
    declare @Skill2 varchar(1)
    declare @Skill3 varchar(1)
    declare @Skill4 varchar(1)
    declare @Skill5 varchar(1)

    declare csrUser cursor for
        select distinct UserID
        from dbo.tblSkills1
        order by 1

    open csrUser

    fetch next from csrUser into @UserID
    while (@@fetch_status = 0)
    begin
        declare csrSkill cursor for
            select Skill
            from dbo.tblSkills1
            where UserID = @UserID
            order by Skill

        set @SkillCount = 1
        set @Skill1 = null
        set @Skill2 = null
        set @Skill3 = null
        set @Skill4 = null
        set @Skill5 = null

        open csrSkill

        fetch next from csrSkill into @Skill
        while (@@fetch_status = 0 and @SkillCount < 6)
        begin
            print @UserID
            print @Skill

            if (@SkillCount = 1)
                set @Skill1 = @Skill
            else if (@SkillCount = 2)
                set @Skill2 = @Skill
            else if (@SkillCount = 3)
                set @Skill3 = @Skill
            else if (@SkillCount = 4)
                set @Skill4 = @Skill
            else if (@SkillCount = 5)
                set @Skill5 = @Skill

            set @SkillCount = @SkillCount + 1

            fetch next from csrSkill into @Skill
        end

        close csrSkill
        deallocate csrSkill

        insert into tblSkills2
        (UserID, Skill1, Skill2, Skill3, Skill4, Skill5)
        values
        (@UserID, @Skill1, @Skill2, @Skill3, @Skill4, @Skill5)

        fetch next from csrUser into @UserID
    end

    close csrUser
    deallocate csrUser
END

答案 4 :(得分:0)

这是另一个例子。这个使用带有标识列的临时表。

SELECT TOP 5 IDENTITY(int) as id, col
  INTO #t
  FROM table
 ORDER BY col

SELECT col FROM #t WHERE id = 5

DROP TABLE #t