0

我在rownumber使用别名列创建自定义时遇到问题。以下是一些示例数据:

question

id   title   
--   --------    
1     xx
2     xxx

..

customerLikeQuestion

Id   QuestionId CustomerId
---------------------------
1       20          xx
2       100         xx 
xx

询问:

SELECT  q.Id,
        (SELECT     COUNT(*) 
         FROM          dbo.CustomerLikeQuestion
         WHERE      (QuestionId = q.Id)) AS LikeCount
FROM dbo.Question AS q
ORDER BY likecount DESC

上一个查询显示:

 id    LikeCount
2136    6
2138    5
2150    5

现在我想放一个rownumber来计算一行的增量顺序。我尝试了以下查询:

SELECT     TOP (100) PERCENT Id,
           (SELECT     COUNT(*) AS Expr1
            FROM          dbo.CustomerLikeQuestion
            WHERE      (QuestionId = q.Id)) AS LikeCount, 
            row_number() over (order by likecount) as RowNum
FROM         dbo.Question AS q
ORDER BY likecount DESC

但它给了我以下错误:

无效列 Likecount。

我确实知道Over()不能使用别名,但是我怎样才能解决这个问题,无论是使用 CTE 还是子查询,我还没有想出任何想法。请帮忙。

正确的结果应该是这样的:

id  likecount, rownum
----------------------    
xx     6        1
xx     5        2 
xx     4        3
..     0        xx
4

1 回答 1

3

试试这个

;WITH LiksCounts
AS
(
    SELECT Id,
           (SELECT     COUNT(*) AS Expr1
            FROM          dbo.CustomerLikeQuestion
            WHERE      (QuestionId = q.Id)) AS LikeCount
    FROM         dbo.Question AS q
     GROUP BY Id
)
SELECT TOP(100) *, row_number() over (order by likecount) as RowNum
fROM LiksCounts
ORDER BY RowNum ASC

现场演示

于 2012-10-14T11:08:24.487 回答