1

我有以下查询:

SELECT * FROM
(
    SELECT 
       a.TeacherID, a.UniversityID, 
       ROW_NUMBER() OVER (ORDER BY a.TeacherID) AS RowNum 
    FROM 
       SelectAll a  
    LEFT JOIN 
       mp_Ratings r ON a.TeacherID = r.TeacherID 
    GROUP BY 
       a.TeacherID, a.UniversityID
) AS TeacherInfo 
WHERE RowNum BETWEEN 10 AND 50

它工作正常。现在,如果我想做类似的事情:

SELECT * FROM
(
    SELECT 
       a.TeacherID, a.UniversityID, 
       ROW_NUMBER() OVER (ORDER BY a.TeacherID) AS RowNum 
    FROM 
       SelectAll a  
    LEFT JOIN 
       mp_Ratings r ON a.TeacherID = r.TeacherID 
    GROUP BY 
       a.TeacherID, a.UniversityID
) AS TeacherInfo 
WHERE RowNum BETWEEN 10 AND 50 AND UniversityID = 2

我什么也没得到,因为UniversityID = 2从行号2991开始。我希望能够Row_Number用每一个不同的UniversityID.

我尝试了以下方法:

SELECT *, ROW_NUMBER() OVER (ORDER BY TeacherID) AS RowNum  
FROM
(
    SELECT 
        a.TeacherID, a.UniversityID 
    FROM 
        SelectAll a  
    LEFT JOIN 
        mp_Ratings r ON a.TeacherID = r.TeacherID 
    GROUP BY 
        a.TeacherID, a.UniversityID
) AS TeacherInfo 
WHERE UniversityID = 2

这为每次搜索带来了新的集合row_numbers,但是如果我尝试这样使用RowNum别名:

SELECT *, ROW_NUMBER() OVER (ORDER BY TeacherID) AS RowNum  
FROM
(
    SELECT 
        a.TeacherID, a.UniversityID 
    FROM 
        SelectAll a  
    LEFT JOIN 
        mp_Ratings r ON a.TeacherID = r.TeacherID 
    GROUP BY 
        a.TeacherID, a.UniversityID
) AS TeacherInfo 
WHERE UniversityID = 2 
  AND RowNum BETWEEN 10 AND 20

我明白了

消息 207,级别 16,状态 1,第 4 行无效的列名称“RowNum”。

我的选择有什么问题?为什么我无法访问RowNum别名?

4

2 回答 2

5

您只需要将WHERE子句移动到内部查询。

SELECT TeacherID, UniversityID, RowNum FROM
(
    SELECT a.TeacherID, a.UniversityID, ROW_NUMBER() OVER 
     (ORDER BY a.TeacherID) AS RowNum FROM SelectAll a
     LEFT JOIN mp_Ratings r 
     ON a.TeacherID = r.TeacherID 
     WHERE UniversityID = 2
     GROUP BY a.TeacherID, a.UniversityID
) as TeacherInfo WHERE RowNum BETWEEN 10 AND 50;

您无法RowNum在查询的外部版本中访问别名,因为别名尚不存在。SELECT被倒数第二次解析,在ORDER BY. WHERE之前处理过SELECT

于 2013-03-26T19:35:36.377 回答
1

使用分区row_number

row_number() over(partition by UniversityID, order by teacherid)
于 2013-08-06T17:35:38.790 回答