Andy Dufresne
2013-05-29 13:33:12 UTC
In SQL Server R2 this query:
SELECT id, code, sequence_number
FROM mytable
returns this data:
id code sequence_number
1 381 0
2 381 1
3 382 0
4 382 1
5 383 0
6 383 1
7 384 0
8 384 1
9 384 1
10 385 0
11 385 1
12 386 0
13 386 1
14 387 0
15 387 1
16 388 0
17 388 1
18 388 1
19 389 0
20 389 1
21 389 1
22 390 0
23 390 1
24 391 0
25 391 1
26 391 1
27 392 0
28 392 1
29 392 1
30 393 0
31 393 1
32 394 0
33 394 1
34 395 0
35 395 1
Analysing the above you see that code 381 has two rows. Those two rows have sequence_numbers of 0 and 1 respectively.
This is repeated until code 384 which has three rows - one row where (sequence_number = 0) but TWO rows where sequence_number = 1
Code 385 and on repeats the origional pattern of 2 rows with sequence_numbers of 0 and 1, until code 388 which has TWO rows where sequence_number = 1 again.
Code 389, 391 and 392 repeat this "1 row for (sequence_number = 0) and two rows for (sequence_number = 1)" pattern.
How do I SELECT the MAX(ID) column for each of the rows where the code and sequence_number columns have TWO or more rows where (sequence_number = 1)?
In other words, I want to SELECT just these rows:
9 384 1
18 388 1
21 389 1
26 391 1
29 392 1
Does that make sense?
Thanks.
SELECT id, code, sequence_number
FROM mytable
returns this data:
id code sequence_number
1 381 0
2 381 1
3 382 0
4 382 1
5 383 0
6 383 1
7 384 0
8 384 1
9 384 1
10 385 0
11 385 1
12 386 0
13 386 1
14 387 0
15 387 1
16 388 0
17 388 1
18 388 1
19 389 0
20 389 1
21 389 1
22 390 0
23 390 1
24 391 0
25 391 1
26 391 1
27 392 0
28 392 1
29 392 1
30 393 0
31 393 1
32 394 0
33 394 1
34 395 0
35 395 1
Analysing the above you see that code 381 has two rows. Those two rows have sequence_numbers of 0 and 1 respectively.
This is repeated until code 384 which has three rows - one row where (sequence_number = 0) but TWO rows where sequence_number = 1
Code 385 and on repeats the origional pattern of 2 rows with sequence_numbers of 0 and 1, until code 388 which has TWO rows where sequence_number = 1 again.
Code 389, 391 and 392 repeat this "1 row for (sequence_number = 0) and two rows for (sequence_number = 1)" pattern.
How do I SELECT the MAX(ID) column for each of the rows where the code and sequence_number columns have TWO or more rows where (sequence_number = 1)?
In other words, I want to SELECT just these rows:
9 384 1
18 388 1
21 389 1
26 391 1
29 392 1
Does that make sense?
Thanks.