1

我有这个 PL/SQL 查询:

SELECT customer_id, table_id, count(table_id) as reserved
FROM { derived table }
GROUP BY customer_id,table_id
ORDER BY reserved DESC

我有这个结果:

http://i.stack.imgur.com/ATfUw.png

所以现在我想获取前 2 行(根据reserved列的最大值),我尝试了这个查询:

SELECT customer_id,table_id,max(reserved) from
(
    SELECT customer_id, table_id, count(table_id) as reserved
    FROM { derived table }
    GROUP BY customer_id,table_id
    ORDER BY reserved DESC
)
GROUP BY customer_id, table_id

我收到与上述相同的结果...

注意:结果只是示例,下次可能会有 3、1 或更多行具有最大值

4

3 回答 3

3
SELECT customer_id,table_id,reserved
FROM (SELECT customer_id,table_id, COUNT(*)as reserved, RANK() OVER (ORDER BY COUNT(*) DESC) AS ct_rank
      FROM { derived table }
      GROUP BY customer_id,table_id
      )sub
WHERE ct_rank = 1

编辑:更改为使用排名

于 2013-05-29T19:33:52.250 回答
0

您的查询非常接近。外部查询应该选择两行,而不是重新进行聚合:

SELECT customer_id, table_id, reserved from
(
    SELECT customer_id, table_id, count(table_id) as reserved
    GROUP BY customer_id,table_id
    ORDER BY reserved DESC
)
where rownum <= 2;
于 2013-05-29T19:48:51.407 回答
0

当您说您想要前 2 行时,我假设您并不是说您总是想要前 2 行,而是您想要具有最大值“保留”的行。

你可以试试:

    SELECT customer_id, table_id, count(table_id) as reserved
    FROM { derived table }
    GROUP BY customer_id, table_id
    HAVING count(table_id) = (
        SELECT top 1 count(table_id)
        FROM { derived table }
        GROUP BY customer_id, table_id
        ORDER BY reserved DESC
    ) 

我知道这可以在 T-SQL 中使用,我猜它也应该在 PL/SQL 中使用。

于 2013-05-29T19:39:03.420 回答