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
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
To explain this behaviour, we need to understand how Oracle processes ROWNUM. When assigningROWNUM to 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 that ROWNUM is greater than 2, no rows are selected and ROWNUM is 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.