我的要求是获取每个客户的最新订单,然后获得前100名记录。
我写了一个如下查询来获取每个客户的最新订单。内部查询工作正常。但我根据结果不知道如何获得前100名。
SELECT * FROM (
SELECT id, client_id, ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
) WHERE rn=1
有什么想法吗?感谢。
答案 0 :(得分:38)
假设create_time包含创建订单的时间,并且您希望100个客户拥有最新订单,您可以:
create_time desc
ROWNUM
查询:
SELECT * FROM (
SELECT * FROM (
SELECT
id,
client_id,
create_time,
ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
)
WHERE rn=1
ORDER BY create_time desc
) WHERE rownum <= 100
更新Oracle 12c
在版本12.1中,Oracle引入了"real" Top-N queries。使用新的FETCH FIRST...
语法,您还可以使用:
SELECT * FROM (
SELECT
id,
client_id,
create_time,
ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
)
WHERE rn = 1
ORDER BY create_time desc
FETCH FIRST 100 ROWS ONLY)
答案 1 :(得分:33)
你应该在oracle中使用rownum来做你想要的事情
where rownum <= 100
另请参阅帮助您的答案
答案 2 :(得分:1)
选择最近更新的前 n 行
SELECT *
FROM (
SELECT *
FROM table
ORDER BY UpdateDateTime DESC
)
WHERE ROWNUM < 101;
答案 3 :(得分:0)
插入db(表客户)的前10个客户:
select * from customers where customer_id <=
(select min(customer_id)+10 from customers)
Last 10 customers inserted into db (table customers):
select * from customers where customer_id >=
(select max(customer_id)-10 from customers)
希望这会有所帮助......
答案 4 :(得分:0)
正如Moneer Kamal所说,您可以简单地做到这一点:
SELECT id, client_id FROM order
WHERE rownum <= 100
ORDER BY create_time DESC;
请注意,在获得第100行后 后完成了排序。这对于不想订购的人可能很有用。
答案 5 :(得分:-3)
试试这个:
SELECT *
FROM (SELECT * FROM (
SELECT
id,
client_id,
create_time,
ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
)
WHERE rn=1
ORDER BY create_time desc) alias_name
WHERE rownum <= 100
ORDER BY rownum;
或TOP:
SELECT TOP 2 * FROM Customers; //But not supported in Oracle
注意:我认为您的内部查询没问题。请分享您的输出。