What's wrong with this request? Can't get ROW_NUMBER () to work

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 )

      

+1


source to share


4 answers


Move Row Criteria to External Selection



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)

      

+6


source


You can do it with 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

      

+1


source


You cannot alias a column in a where clause because the where clause is processed before the Select clause.

EDITED:

You can also just add a subquery to the where clause

Where ((SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn)) < 20,

      

or without using the whole Row_Number,

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

      

0


source


check which version of SQL Server database you are using. Row_number is added from SQL Server 2005 onwards. It will not support SQL Server 2000

0


source







All Articles