我有这个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
所以现在我想获得前两行(根据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个或更多行具有最大值,下次
答案 0 :(得分: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
编辑:已更改为使用排名
答案 1 :(得分:0)
当你说你想要前两行时,我假设你并不是说你总是想要前两行 - 而是你想要那些最大值为'reserved'的行。
你可以尝试:
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中。
答案 2 :(得分: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;