按列别名运行Order

时间:2014-01-23 06:46:22

标签: sql sql-server sql-server-2008

我正在尝试在northwind数据库上运行以下SQL查询:

SELECT * FROM (
    SELECT DISTINCT ROW_NUMBER() OVER (ORDER BY Joinning DESC) rownum,
    LastName, Country, HireDate AS Joinning
   FROM  Employees
   WHERE  Region IS NOT NULL
   ) r

它给了我错误:

Invalid column name 'Joinning'.

分页需要'rownumber'。

有人可以建议我如何使用生成的rownumber对加入别名进行排序?

- 可能的解决方法

刚刚找到了解决方法;如果出现任何问题或需要更改,请提出建议:

SELECT ROW_NUMBER() OVER (ORDER BY Joinning DESC) rownum,* FROM (
    SELECT  
    LastName, Country, HireDate AS Joinning

   FROM  Employees
   WHERE  Region IS NOT NULL
   ) r

- 在行号上放置更多where子句(我想为分页做什么):

With myres as(
   SELECT ROW_NUMBER() OVER (ORDER BY Joinning DESC) rownum,* FROM (
    SELECT  
       LastName, Country, HireDate AS Joinning
       FROM  Employees
       WHERE  Region IS NOT NULL
     ) a
) Select * from myres where myres.rownum > 0 and myres.rownum < = 0+20

3 个答案:

答案 0 :(得分:1)

尝试

SELECT * FROM (
SELECT DISTINCT ROW_NUMBER() OVER (ORDER BY HireDate DESC) rownum,
LastName, Country, HireDate AS Joinning
FROM  Employees
WHERE  Region IS NOT NULL
) r

答案 1 :(得分:0)

希望你加入你的桌子。 order by子句通常在查询的最后一个给出,如下所示:

SELECT * FROM(     SELECT DISTINCT ROW_NUMBER()rownum,     LastName,Country,HireDate AS Joinning)    来自员工    WHERE Region IS NOT NULL ORDER BY Joinning DESC)

希望这能帮到你!

答案 2 :(得分:0)

使用该字段的原始名称,即可正常使用 HireDate

SELECT * FROM (
    SELECT DISTINCT ROW_NUMBER() OVER (ORDER BY HireDate DESC) rownum,
    LastName, Country, HireDate AS Joinning
   FROM  Employees
   WHERE  Region IS NOT NULL
   ) r