I have three columns -
TheDate
- Obviously a date.TheID
- A strictly increasing ID.TheType
- A Record t
This is complicated. First you must find consecutive date records, so with
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
you would identify 2014-07-12 as one occurrence for the first three records and another for the last record. The second record would have to get position #3 in your results, not #5.
You achieve this by giving consecutive records a group key by using first LAG
to look into the previous record, thus creating a flag on group change, and then cumulating these flags.
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;