没有为ROW_NUMBER()查询返回结果

时间:2013-08-07 21:49:41

标签: sql-order-by where-clause resultset having-clause row-number

对于以下查询,我收到“未返回结果”:

SELECT 
    Referer 
FROM 
    (SELECT 
        ROW_NUMBER() OVER (ORDER BY CT.Referer ASC) AS RowNum, 
        CT.Referer, CT.LastModified
     FROM 
        ClickTrack CT 
     JOIN 
        OrderTrack OT ON OT.ClickTrackID = CT.ClickTrackID              
     GROUP BY 
        CT.Referer, CT.LastModified
     HAVING 
        LEN(CT.Referer) > 0) as num 
WHERE 
    RowNum = 1 
    AND LastModified BETWEEN '07/06/2013' and '08/05/2013'

奇怪的是,当我离开RowNum = 1时,我会得到完整的值列表。我需要一次获得一个,但要分配给一个变量并放入一个临时表。

结束查询将在while循环中使用标量变量代替日期范围和RowNum比较。

感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

我认为RowNum 1可能没有您选择的日期。也许把日期选择放在里面,以便你知道第一个匹配。

    SELECT Referer 
    FROM (SELECT ROW_NUMBER() OVER (ORDER BY CT.Referer ASC) 
    AS RowNum, CT.Referer, CT.LastModified
    FROM ClickTrack CT 
    JOIN OrderTrack OT ON OT.ClickTrackID = CT.ClickTrackID    
    WHERE CT.LastModified BETWEEN '07/06/2013' and '08/05/2013'          
    GROUP BY CT.Referer, CT.LastModified
    HAVING LEN(CT.Referer) > 0) as num 
    WHERE RowNum = 1