基于ROW_Number的SQL查询无法正常工作

时间:2010-11-18 18:46:44

标签: sql sql-server tsql analytic-functions

基本上我正在尝试对只包含图像的页面进行查询。我需要提供tripID号码,然后提供ROWID(因为可能有多个图像)来接收单个图像。我将循环,直到每个图像都在html的相应图像框中。

此代码似乎不起作用(我得到无效的列名'ROWID'),但如果我删除AND ROWID ='1',它将返回所有图像及其行ID如下:

ROWID      PHOTO
    1      32jjr3h2jh23hj4h32jh42ll23j42 
    2       HU8308DJAOID9ASIDJI32C89EE29

-

Select ROW_NUMBER() OVER (ORDER BY Photo ASC) AS ROWID, TBL_Photo.Photo
        From TBL_Photo
        left join TBL_TripDetails
        ON TBL_Photo.TripID=TBL_TripDetails.pkiTripID
        Where pkiTripID = '121' AND ROWID = '1'

1 个答案:

答案 0 :(得分:5)

您不能在WHERE子句中引用列别名 - 您需要使用子查询或CTE:

子查询示例:

SELECT x.rowid,
       x.photo
  FROM (SELECT ROW_NUMBER() OVER (ORDER BY p.photo) AS ROWID, 
               p.photo
          FROM TBL_PHOTO p
     LEFT JOIN TBL_TRIPDETAILS td ON td.pkitripid = p.tripid 
         WHERE td.pkiTripID = '121') x
 WHERE x.rowid = 1

CTE示例:

WITH example AS (
        SELECT ROW_NUMBER() OVER (ORDER BY p.photo) AS ROWID, 
               p.photo
          FROM TBL_PHOTO p
     LEFT JOIN TBL_TRIPDETAILS td ON td.pkitripid = p.tripid 
         WHERE td.pkiTripID = '121')
SELECT x.rowid,
       x.photo
  FROM example x
 WHERE x.rowid = 1

效果

这两个选项之间没有性能差异,但并非所有数据库都支持WITH语法。