1

我试图使用ROW_NUMBER()子句来检索特定的行号

当我执行这个查询

SELECT 
student.Aca_num,id_num,student.name,dob,pic,class.name,
student.tell,student.mobile1,mobile2,student.Email,nach.name,dist,notes
FROM
student,[user],users_classes,class,nach
WHERE
((class.ID)=student.class)
and
((nach.ID)=student.nach)
and
((student.class)=users_classes.Class_ID)
AND
((users_classes.[User_ID])=[user].ID)
AND
(([user].ID)=3)

查询的结果

现在我需要使用Row Number()此查询通过指定行号仅检索一行。

我用Row Number()这样

SELECT * FROM
    (SELECT ROW_NUMBER() OVER (ORDER BY name) AS Row, * FROM Student) AS EMP
WHERE Row = 3

此查询返回third学生表的行

但是Row Number()与多个表一起使用时出现错误,例如 (student,class)

SELECT * FROM
    (SELECT ROW_NUMBER() OVER (ORDER BY student.name) AS Row, * FROM Student,Class) AS EMP
WHERE Row = 3

它给了我这个错误

消息 8156,级别 16,状态 1,第 10 行 为“EMP”多次指定了“名称”列。

如何使用Row Number()带有多个表的子句返回特定的行号|

提前致谢

问候 ...

4

2 回答 2

2

这与 . 无关ROW_NUMBER()

在 yourStudentClass表中,您都有一个名为Name. 创建子查询时,结果集中的列名必须不同。

所以不要使用*, 明确地命名列,包括(如果你必须同时拥有两个名称)一个别名:

SELECT * FROM
    (SELECT ROW_NUMBER() OVER (ORDER BY s.name) AS Row, s.Name as StudentName,c.Name as ClassName FROM Student s,Class c) AS EMP
WHERE Row = 3

当然,目前,您正在两个表之间执行笛卡尔连接。您更有可能想以某种方式加入表格,例如

... FROM Student s INNER JOIN Class c on s.class = c.id ...
于 2013-01-09T08:03:09.150 回答
1

我希望这是有用的;

;WITH Emp AS
(
            -- Avoid using reserved words like [Row] (changed to nRow)
    SELECT   ROW_NUMBER() OVER (ORDER BY student.name) AS nRow 
            -- You cannot use * because your tables have columns with matching names
            -- Make sure that the columns you require are unique in their name or are aliased
            -- to be unique
            ,S.Col AS Foo
            ,C.Col AS Bar 
    FROM Student    S
    --  Your FROM expression [FROM Student,Class] will result effectively in a CROSS JOIN
    --  Clarify your join condition if you do not want a cartesian product
    JOIN Class      C ON S.Col = C.Col
)
SELECT *
FROM Emp
WHERE nRow = 3
于 2013-01-09T08:19:12.923 回答