How can i get a gap from a history table for repeating groups over time

Hadrien

I have a historical table with data like as bellow :

SK ID STATUS EFF_DT EXP_DT 
1 486007909 APP 7/22/2009  8/22/2009
2 486007909 APP 8/22/2009  10/01/2009
3 486007909 CAN 10/01/2009 11/01/2009
4 486007909 CAN 11/02/2009 12/12/2009
5 486007909 APP 12/12/2009 NULL

The EXP_DT is null mean that the row is active.

I want to return a group of data each time Status changes

The expected result like as bellow :

SK ID STATUS EFF_DT EXP_DT                 GAP
1 486007909 APP 7/22/2009  8/22/2009        1
2 486007909 APP 8/22/2009  10/01/2009       1
3 486007909 CAN 10/01/2009 11/01/2009       2
4 486007909 CAN 11/02/2009 12/12/2009       2
5 486007909 APP 12/12/2009 NULL             3

Thanks for help !

Charlieface

This is classic gaps-and-islands problem.

We can solve it by using LAG to check for differences, then a windowed COUNT to get the GAP number.

You may want to add a partitioning clause, such as PARTITION BY ID

SELECT *,
  GAP = COUNT(IsDiff) OVER (ORDER BY EFF_DT ROWS UNBOUNDED PRECEDING)
FROM (
    SELECT *,
      IsDiff = CASE WHEN LAG(STATUS, 1, '') OVER (ORDER BY EFF_DT) <> STATUS THEN 1 END
    FROM YourTable t
) t

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

How can I increase Dataframe time by 5 minutes gap?

How can I remove the gap from the top of page?

how can I get groups of some user, then filter groups by some name?

How can I get this table in HTML?

How can i loop over an array to get jquery properties?

How can I get specific documents using conditions from flutter real-time database

How I can get distinct records from laravel table using elequent model?

How can I get a "flat" output of data from a parent / child table with LINQ

How can i generate a "connect time over time" graph in grafana with jmeter+influxDB+Grafana Stack?

how I can get the value from datalist

How I can get entitymanager from crudrepository

How can I get HttpServletRequest from ServletContext?

How can I get time zone information for an SMS with Twilio?

How can I prevent or avoid interactive function input from being saved to the minibuffer-history?

How can I convert character vector with time into Time class and get a total amount of time after summing in r

How can I return multiple levels/groups of values from a multi-index dataframe?

How can I get the background color of an HTML table's row?

How can I get the results of many queries into 1 table?

How can i take time difference from minutes and hour?

How can I sum/subtract time values from same row

How to I get current time from angular material Date picker?

in pivot table i stored post_id and category_id how can i get my Post category name from pivot table?

How can I select unique results from a table based on a column?

How can I scrape table from PHP website using R?

How can I use purrr to match records from a lookup table?

How can I delete a column by index from a kdb table?

How can i use information from another table in a trigger?

How can I add a new attribute from another table to a serializer?

Laravel: How do I get data from this pivot table?

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    ViewPager2 мигает / перезагружается при смахивании

  3. 3

    Merging legends in plotly subplot

  4. 4

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  5. 5

    Как добавить заголовок в легенду для двух независимых групп, состоящих из трех подгрупп?

  6. 6

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  7. 7

    Невозможно запустить iReports 5.6.0 с Netbeans 8 и JDK 1.8

  8. 8

    выделение строк jQuery DataTables

  9. 9

    JavaFX TextArea как установить текст с автоматическим переносом новой строки

  10. 10

    Как я могу нарисовать заполненный прямоугольник в JFreeChart?

  11. 11

    Как в точности работает внутренний пул потоков Nodejs?

  12. 12

    Камунда - Фильтровать список задач по назначенной группе

  13. 13

    How do I search for an entry out of two SQL tables and know which table it came from?

  14. 14

    Как фильтровать таблицу SQLite3 в PyQt5

  15. 15

    Как запустить скрипт node js из скрипта powershell и использовать вывод скрипта node js в скрипте powershell?

  16. 16

    Создание гистограммы для 10 монет, перевернутых одновременно 1000 раз с помощью R

  17. 17

    How to convert C++/CLI string to const char*

  18. 18

    Элемент "эллипс", созданный с помощью JS, не отображается в HTML

  19. 19

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  20. 20

    Slick Carousel + Проблема форматирования аккордеона

  21. 21

    Два ArrayList один адаптер RecyclerView

популярныйтег

файл