Sliding certain records to the end of a run of the same date

前端 未结 3 2002
名媛妹妹
名媛妹妹 2021-01-26 10:59

I have three columns -

  • TheDate - Obviously a date.
  • TheID - A strictly increasing ID.
  • TheType - A Record t
3条回答
  •  旧巷少年郎
    2021-01-26 11:26

    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;
    

提交回复
热议问题