这个查询有什么问题?无法让ROW_NUMBER()工作

时间:2008-12-10 20:58:06

标签: sql sql-server tsql row-number

SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn) as Row,
        hrl.unq, hrl.LcnsId, hc.Business,hc.Name,hc.Phone,
        hrl.Frn,hrl.CallSign, hrl.gsamarkettypeid, 
        gmt.[Market Type Code] + ' - ' + gmt.gsamarkettype,
        hrl.gsalatitude,hrl.gsalongitude,
        rsc.RadioServiceCode + ' - ' + rsc.RadioService, 
                    GrantDt, ExpirationDt, EffectiveDt, 
        CancellationDt
        FROM dbo.sbi_f_HldrRgstrtnLcns hrl
        INNER JOIN dbo.sbi_f_HldrCntcts hc on 
                    hc.CallSign = hrl.CallSign
        INNER JOIN dbo.sbi_l_radioservicecodes rsc on 
                    rsc.radioservicecodeid = hrl.radioservicecodeid
        LEFT OUTER JOIN dbo.sbi_l_GSAMarketTypes gmt on 
                    gmt.GSAMarketTypeId = hrl.GSAMarketTypeId
        WHERE hc.Entity_Type = 'L'  AND hrl.LicenseStatusId IN (1)
        and Row >=1 and Row <= 20) -- The error occurs here,
                    -- it says incorrect syntax near )

4 个答案:

答案 0 :(得分:6)

将您的行标准移动到外部选择

SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn) as Row,
     ...
               WHERE hc.Entity_Type = 'L'  AND hrl.LicenseStatusId IN (1)
              ) T
WHERE T.Row >=1 and T.Row <= 20)

答案 1 :(得分:1)

您可以使用CTE执行此操作:

WITH NumberedRows AS
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY hrn.Frl) AS RowNum,
        ...
    WHERE 
        hc.Entity_Type = 'L'
        AND hrl.LicenseStatusId IN (1)
)
SELECT
    *
FROM
    NumberedRows
WHERE
    RowNum <= 20

答案 2 :(得分:0)

您不能在where子句中为列使用别名,因为where子句是在Select子句之前处理的。

已编辑:

您也可以在where子句

中添加子查询
Where ((SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn)) < 20,

或根本不使用Row_Number,

Where (Select Count(*) 
From dbo.sbi_f_HldrRgstrtnLcns 
Where Frn < hrl.Frn) < 20

答案 3 :(得分:0)

检查您使用的是哪个版本的sql server数据库。 row_number是从sql server 2005开始添加的。它不支持sql server 2000