我尝试使用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()
与多个表格(例如(学生,班级)
SELECT * FROM
(SELECT ROW_NUMBER() OVER (ORDER BY student.name) AS Row, * FROM Student,Class) AS EMP
WHERE Row = 3
它给了我这个错误
Msg 8156,Level 16,State 1,Line 10 The column' Name'被指定了 多次为EMP'。
如何使用多个Table的Row Number()
子句返回特定的行号|
提前致谢
问候......
答案 0 :(得分:2)
这与ROW_NUMBER()
没有任何关系。
在Student
和Class
表格中,您都有一个名为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 ...
答案 1 :(得分: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