MSSQL Paginate带有求和函数

时间:2012-04-17 11:39:55

标签: sql sql-server pagination

我有一个表格,其行包含特定日期的某个类别的点击次数。像这样:

ID  CatID   Date                 Count
1   DADB    2011-11-04 00:00:00      3
2   DCBC    2011-11-04 00:00:00      9
3   DADH    2011-11-04 00:00:00      9

因此,要显示两个日期之间每个类别的总计数,我会这样做:

SELECT WebClicksCategory.CatID, sum(WebClicksCategory.Count) as Count
FROM [Web].[dbo].[WebClicksCategory]
WHERE Date >= '2011-04-17 00:00:00.000'
AND Date <= '2012-04-17 00:00:00.000'
GROUP BY WebClicksCategory.CatID
ORDER BY Count desc 

但是,如果我想对这些结果进行分页并执行以下操作:

SELECT * FROM 
( SELECT  row_number() OVER (order by Count) AS rownum, 
WebClicksCategory.CatID, sum(WebClicksCategory.Count) as Count 
FROM [Web].[dbo].[WebClicksCategory]
WHERE Date >= '2011-04-17 00:00:00.000'
AND Date <= '2012-04-17 00:00:00.000'
GROUP BY WebClicksCategory.CatID
) AS A
WHERE A.rownum BETWEEN (50) AND (200)

但我得到一个'列WebClicksCategory.Count在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中'错误。还有其他方法可以对结果进行分页吗?

1 个答案:

答案 0 :(得分:0)

问题不在于将聚合包括在内,而是将其包含在OVER子句中:

( SELECT  row_number() OVER (order by Count) AS rownum, 

所以我的建议是:

SELECT rownum, CatID, Count FROM 
( SELECT  row_number() OVER (order by Count) AS rownum, CatID, Count
FROM 
  ( SELECT WebClicksCategory.CatID, sum(WebClicksCategory.Count) as Count 
    FROM [Web].[dbo].[WebClicksCategory]
    WHERE Date >= '2011-04-17 00:00:00.000'
    AND Date <= '2012-04-17 00:00:00.000'
    GROUP BY WebClicksCategory.CatID
  ) AS B
) AS A
WHERE A.rownum BETWEEN (50) AND (200)