How to use windowing functions to find gaps in sequences grouped by a column, in PostgreSQL





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







0















I have a table structure which has 2 columns: client_id, order_no, and both are integers. I'd like to find gaps in order_no in the data so that, for example, for a table containing these rows:



42, 1
43, 1
42, 2
43, 5
43, 6
42, 3


the output contains the client_id, and boundaries of the gaps, like this:



43, 2, 4


Note that there's no row with client_id=42 because there are no gaps in its data.



I've tried this for the core part of the query:



select 
client_id,
order_no as start_order_no,
lead(order_no) over (order by client_id, order_no) as end_order_no


but that apparently doesn't do what I want, and I suspect it's because of client_id in the OVER part.










share|improve this question
















bumped to the homepage by Community 51 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.











  • 2





    You probably meant partition by client_id order by order_no

    – mustaccio
    Nov 1 '18 at 18:41


















0















I have a table structure which has 2 columns: client_id, order_no, and both are integers. I'd like to find gaps in order_no in the data so that, for example, for a table containing these rows:



42, 1
43, 1
42, 2
43, 5
43, 6
42, 3


the output contains the client_id, and boundaries of the gaps, like this:



43, 2, 4


Note that there's no row with client_id=42 because there are no gaps in its data.



I've tried this for the core part of the query:



select 
client_id,
order_no as start_order_no,
lead(order_no) over (order by client_id, order_no) as end_order_no


but that apparently doesn't do what I want, and I suspect it's because of client_id in the OVER part.










share|improve this question
















bumped to the homepage by Community 51 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.











  • 2





    You probably meant partition by client_id order by order_no

    – mustaccio
    Nov 1 '18 at 18:41














0












0








0








I have a table structure which has 2 columns: client_id, order_no, and both are integers. I'd like to find gaps in order_no in the data so that, for example, for a table containing these rows:



42, 1
43, 1
42, 2
43, 5
43, 6
42, 3


the output contains the client_id, and boundaries of the gaps, like this:



43, 2, 4


Note that there's no row with client_id=42 because there are no gaps in its data.



I've tried this for the core part of the query:



select 
client_id,
order_no as start_order_no,
lead(order_no) over (order by client_id, order_no) as end_order_no


but that apparently doesn't do what I want, and I suspect it's because of client_id in the OVER part.










share|improve this question
















I have a table structure which has 2 columns: client_id, order_no, and both are integers. I'd like to find gaps in order_no in the data so that, for example, for a table containing these rows:



42, 1
43, 1
42, 2
43, 5
43, 6
42, 3


the output contains the client_id, and boundaries of the gaps, like this:



43, 2, 4


Note that there's no row with client_id=42 because there are no gaps in its data.



I've tried this for the core part of the query:



select 
client_id,
order_no as start_order_no,
lead(order_no) over (order by client_id, order_no) as end_order_no


but that apparently doesn't do what I want, and I suspect it's because of client_id in the OVER part.







postgresql window-functions gaps-and-islands






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 1 '18 at 19:03









MDCCL

6,85331745




6,85331745










asked Nov 1 '18 at 18:30









Ivan VorasIvan Voras

27019




27019





bumped to the homepage by Community 51 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 51 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.










  • 2





    You probably meant partition by client_id order by order_no

    – mustaccio
    Nov 1 '18 at 18:41














  • 2





    You probably meant partition by client_id order by order_no

    – mustaccio
    Nov 1 '18 at 18:41








2




2





You probably meant partition by client_id order by order_no

– mustaccio
Nov 1 '18 at 18:41





You probably meant partition by client_id order by order_no

– mustaccio
Nov 1 '18 at 18:41










1 Answer
1






active

oldest

votes


















0














You should use a CTE or a subquery to get the lead order_no first.






select client_id,
order_no + 1 as c1,
no - 1 c2
from (select client_id,
order_no,
lead(order_no)
over (partition by client_id order by client_id, order_no) as no
from tbl) ct
where no is not null
and no - order_no > 1;






with ct as
(
select client_id,
order_no,
lead(order_no)
over (partition by client_id order by client_id, order_no) as no
from tbl
)
select client_id,
order_no + 1 as c1,
no - 1 c2
from ct
where no is not null
and no - order_no > 1;



client_id | c1 | c2
--------: | -: | -:
43 | 2 | 4



db<>fiddle here






share|improve this answer
























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "182"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f221564%2fhow-to-use-windowing-functions-to-find-gaps-in-sequences-grouped-by-a-column-in%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You should use a CTE or a subquery to get the lead order_no first.






    select client_id,
    order_no + 1 as c1,
    no - 1 c2
    from (select client_id,
    order_no,
    lead(order_no)
    over (partition by client_id order by client_id, order_no) as no
    from tbl) ct
    where no is not null
    and no - order_no > 1;






    with ct as
    (
    select client_id,
    order_no,
    lead(order_no)
    over (partition by client_id order by client_id, order_no) as no
    from tbl
    )
    select client_id,
    order_no + 1 as c1,
    no - 1 c2
    from ct
    where no is not null
    and no - order_no > 1;



    client_id | c1 | c2
    --------: | -: | -:
    43 | 2 | 4



    db<>fiddle here






    share|improve this answer




























      0














      You should use a CTE or a subquery to get the lead order_no first.






      select client_id,
      order_no + 1 as c1,
      no - 1 c2
      from (select client_id,
      order_no,
      lead(order_no)
      over (partition by client_id order by client_id, order_no) as no
      from tbl) ct
      where no is not null
      and no - order_no > 1;






      with ct as
      (
      select client_id,
      order_no,
      lead(order_no)
      over (partition by client_id order by client_id, order_no) as no
      from tbl
      )
      select client_id,
      order_no + 1 as c1,
      no - 1 c2
      from ct
      where no is not null
      and no - order_no > 1;



      client_id | c1 | c2
      --------: | -: | -:
      43 | 2 | 4



      db<>fiddle here






      share|improve this answer


























        0












        0








        0







        You should use a CTE or a subquery to get the lead order_no first.






        select client_id,
        order_no + 1 as c1,
        no - 1 c2
        from (select client_id,
        order_no,
        lead(order_no)
        over (partition by client_id order by client_id, order_no) as no
        from tbl) ct
        where no is not null
        and no - order_no > 1;






        with ct as
        (
        select client_id,
        order_no,
        lead(order_no)
        over (partition by client_id order by client_id, order_no) as no
        from tbl
        )
        select client_id,
        order_no + 1 as c1,
        no - 1 c2
        from ct
        where no is not null
        and no - order_no > 1;



        client_id | c1 | c2
        --------: | -: | -:
        43 | 2 | 4



        db<>fiddle here






        share|improve this answer













        You should use a CTE or a subquery to get the lead order_no first.






        select client_id,
        order_no + 1 as c1,
        no - 1 c2
        from (select client_id,
        order_no,
        lead(order_no)
        over (partition by client_id order by client_id, order_no) as no
        from tbl) ct
        where no is not null
        and no - order_no > 1;






        with ct as
        (
        select client_id,
        order_no,
        lead(order_no)
        over (partition by client_id order by client_id, order_no) as no
        from tbl
        )
        select client_id,
        order_no + 1 as c1,
        no - 1 c2
        from ct
        where no is not null
        and no - order_no > 1;



        client_id | c1 | c2
        --------: | -: | -:
        43 | 2 | 4



        db<>fiddle here







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 1 '18 at 21:55









        McNetsMcNets

        16.4k42261




        16.4k42261






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Database Administrators Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f221564%2fhow-to-use-windowing-functions-to-find-gaps-in-sequences-grouped-by-a-column-in%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL Server 17 - Attemping to backup to remote NAS but Access is denied

            Always On Availability groups resolving state after failover - Remote harden of transaction...

            Restoring from pg_dump with foreign key constraints