复杂的SQL分页查询

时间:2011-11-08 08:37:45

标签: sql sql-server tsql pagination

我正在使用this问题的解决方案对我的数据进行分页。

我现在需要将此解决方案用于更复杂的查询。 IE浏览器。括号内的SELECT具有连接和聚合函数。

这是我用作参考的解决方案:

;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit

我需要纳入上述解决方案的查询:

SELECT users.indicator, COUNT(*) as 'queries' FROM queries
INNER JOIN calls ON queries.call_id = calls.id
INNER JOIN users ON calls.user_id = users.id
WHERE queries.isresolved=0 AND users.indicator='ind1'
GROUP BY users.indicator ORDER BY queries DESC

我怎样才能做到这一点?到目前为止,我已经通过移除ORDER BY queries DESC部分并将其放在行ROW_NUMBER() OVER (ORDER BY ...) AS RowNum中使其工作,但是当我这样做时,它不允许我按该列排序(“无效的列名称'查询'。“)。

我需要做些什么才能让这个专栏订购?

编辑:使用SQL Server 2008

2 个答案:

答案 0 :(得分:1)

尝试ORDER BY COUNT(*)DESC。它适用于MySQL ......不确定SQL Server 2008

答案 1 :(得分:0)

我认为查询count(*)列的别名 然后像这样使用

SELECT users.indicator, COUNT(*) as 'queries' FROM queries
INNER JOIN calls ON queries.call_id = calls.id
INNER JOIN users ON calls.user_id = users.id
WHERE queries.isresolved=0 AND users.indicator='ind1'
GROUP BY users.indicator ORDER BY COUNT(*) DESC

http://oops-solution.blogspot.com/2011/11/string-handling-in-javascript.html