SQL Server ORDER BY [aggregation] DESC / ASC

时间:2012-04-05 23:06:37

标签: sql sql-server

我希望能够通过升序或降序对[评论]进行排序。我已尝试在“order by”子句中再次执行聚合,但这不起作用。我也尝试在子查询之外进行排序,这让我使用了别名[comment],但是只在第0行和第10行之间进行了排序。

此查询是更大查询的较小版本。


SELECT *
FROM   (SELECT ISNULL((SELECT COUNT("order")
                       FROM   order_comment
                       WHERE  "order" = "order"."id"
                       GROUP  BY "order"), 0)                 AS [comment],
               Row_number() OVER (ORDER BY "order"."id" DESC) AS [rownum]
        FROM   [order]
        WHERE  ISNULL((SELECT COUNT("order")
                       FROM   order_comment
                       WHERE  "order" = "order"."id"
                       GROUP  BY "order"), 0) > 0) AS [filter]
WHERE  [rownum] BETWEEN 0 AND 10

在MySql中如此简单!


SELECT Ifnull((SELECT COUNT(`order`)
               FROM   order_comment
               WHERE  `order` = `order`.`id`
               GROUP  BY `order`), 0) AS `comment`
FROM   `order`
HAVING `comment` > 0
ORDER  BY `comment` DESC
LIMIT  0, 10  

3 个答案:

答案 0 :(得分:5)

按照最新的编辑嫌疑人你想要这样的东西

;WITH oc AS
(
SELECT [order], 
       COUNT([order]) AS order_count
FROM   order_comment 
GROUP  BY [order]
), occ AS
(
SELECT o.*,
       order_count AS comment,
       ROW_NUMBER() OVER (ORDER BY order_count DESC) AS  [rownum]
FROM [order] o
INNER JOIN oc ON oc.[order] = o.id
)
SELECT *
FROM occ 
WHERE  [rownum] BETWEEN 0 AND 10
ORDER BY [rownum]

INNER JOIN已排除order_comment

中没有子行的所有行

答案 1 :(得分:0)

我认为您不知道可以将OVER clause与聚合函数一起使用。

COUNT(order) OVER(PARTITION BY id) AS [comment]
....
ORDER BY [comment]

答案 2 :(得分:0)

在SQL Server中,您可以按查询中的列号排序,如ORDER BY 1中所示 更多信息http://blog.sqlauthority.com/2010/12/27/sql-server-order-by-columnname-vs-order-by-columnnumber/

SELECT *
FROM   (SELECT ISNULL((SELECT COUNT("order")
                      FROM   order_comment
                   WHERE  "order" = "order"."id"
                   GROUP  BY "order"), 0)                 AS [comment],
           Row_number() OVER (ORDER BY "order"."id" DESC) AS [rownum]
    FROM   [order]
    WHERE  ISNULL((SELECT COUNT("order")
                   FROM   order_comment
                   WHERE  "order" = "order"."id"
                   GROUP  BY "order"), 0) > 0) AS [filter]
WHERE  [rownum] BETWEEN 0 AND 10
 ORDER BY 1