Oracle: Почему rownum не работает с group by?
- Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
08.07.2011
У меня есть следующий запрос
select oc.soc_sec_num from om_customer oc, om_subscription os where os.customer_id = oc.customer_id and os.state_code = 'ACTIVE' and os.activation_date > to_char(sysdate-365, 'dd.mm.yyyy') group by oc.soc_sec_num having count(oc.billing_id) > 2 and count(oc.billing_id) < 20
вибирается более 100 записей. Теперь мне нужно ограничить выборку только одной строкой.
select oc.soc_sec_num from om_customer oc, om_subscription os where os.customer_id = oc.customer_id and os.state_code = 'ACTIVE' and os.activation_date > to_char(sysdate-365, 'dd.mm.yyyy') and rownum = 1 group by oc.soc_sec_num having count(oc.billing_id) > 2 and count(oc.billing_id) < 20
и вообще нет никаких записей. В чем загвоздка?
08.07.2011
#1
нашел обход для rownum
select soc_sec_num from ( select oc.soc_sec_num from om_customer oc, om_subscription os where os.customer_id = oc.customer_id and os.state_code = 'ACTIVE' and os.activation_date > to_char(sysdate-365, 'dd.mm.yyyy') group by oc.soc_sec_num having count(oc.billing_id) > 2 and count(oc.billing_id) < 20 ) where rownum = 1;
но все равно не сильно прозрачно, как работает rownum
13.07.2011
#2
Попробуй исправить во втором
Попробуй исправить во втором запросе так:
where rownum < 2
13.07.2011
#3
почему rownum не работает в первом запросе?
второй запрос работает нормально, вопрос есть и до сих пор, почему rownum не работает в первом запросе?
06.09.2011
#4
причина ясна
http://blog.lishman.com/2008/03/rownum.htmlTo explain this behaviour, we need to understand how Oracle processes
ROWNUM. When assigningROWNUMto a row, Oracle starts at 1 and only only increments the value when a row is selected; that is, when all conditions in the WHERE clause are met. Since our condition requires thatROWNUMis greater than 2, no rows are selected andROWNUMis never incremented beyond 1.
The bottom line is that conditions such as the following will work as expected... WHERE rownum = 1;
.. WHERE rownum <= 10;
While queries with these conditions will always return zero rows... WHERE rownum = 2;
.. WHERE rownum > 10;







