Esto es complicado. Primero debe encontrar registros de fechas consecutivas, así que con
thedate theid thetype 2014-07-12 5001 59 2014-07-12 5002 101 2014-07-12 5003 88 2014-07-13 5004 10 2014-07-12 5005 60
identificaría 2014-07-12 como una ocurrencia para los primeros tres registros y otra para el último registro. El segundo registro tendría que obtener la posición n.° 3 en sus resultados, no la n.° 5.
Esto se logra dando a los registros consecutivos una clave de grupo usando el primer LAG
para buscar en el registro anterior, creando así un indicador de cambio de grupo y luego acumulando estos indicadores.
select thedate, theid, thetype
from
(
select
thedate, theid, thetype,
sum(new_group) over (order by theid) as group_key
from
(
select
thedate, theid, thetype,
case when lag(thedate) over (order by theid) = thedate then 0 else 1 as new_group
from mytable
) marked
) grouped
order by
group_key,
case when thetype = 101 then 1 else 0 end,
theid;