Note that there are some explanatory texts on larger screens.

plurals
  1. POfind first row based on a cycle size
    primarykey
    data
    text
    <p>I have a table of cards and a table of moves (on a card), like:</p> <pre><code>declare @cards table ( id_card int, cycle int ) insert into @cards (id_card, cycle) values (1, 10) declare @moves table ( id_move int, id_card int, quantity int ) insert into @moves (id_move, id_card, quantity) values (1, 1, 2) insert into @moves (id_move, id_card, quantity) values (2, 1, 4) insert into @moves (id_move, id_card, quantity) values (3, 1, 2) insert into @moves (id_move, id_card, quantity) values (4, 1, 8) insert into @moves (id_move, id_card, quantity) values (5, 1, 2) </code></pre> <p>The problem: each card gets a cycle size, and each move gets a quantity. So, a card cycle size 10 and 18 moves means 1 full cycle plus 8 moves. I have to find the last cycle first move (the move id 4 in the given example). The problem sounds (at first) trivial, but I'm getting so many troubles to find the move that I think I'm doing something very wrong.</p> <p>I came up with a query that gives where the last cycle first move starts position, but I'm not finding anywhere to go from there.</p> <pre><code>select id_card, case when value &gt; quantity then value - quantity else value end value from ( select f.id_card, f.quantity, f.quantity - f.quantity % cards.cycle + 1 value from ( select id_card, sum(quantity) quantity from @moves group by id_card ) f join @cards cards on cards.id_card = f.id_card ) f </code></pre> <p>Expected output:</p> <pre><code>id_move 4 </code></pre> <p>Any ideas? I can make any modifications to make the problem easier.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload