I have a table that has a sequence number assigned in the form of 12-12345-1. As the sequence increases, the last digit increments by 1, so the next sequence number would be 12-12345-2. What I need to do is query the table to find all sequence numbers ending with '1' that do not have a '2' or greater. The sequence number is a varchar field, if that matters.
SELECT *
FROM YourTable T1
LEFT JOIN YourTable T2
ON LEFT(T1.seq_no, 8) = LEFT(T2.seq_no, 8)
AND T1.seq_no < T2.seq_no
WHERE RIGHT(T1.seq_no, 2) = '-1'
AND T2.seq_no IS NULL;
SELECT *
FROM YourTable T1
WHERE RIGHT(T1.seq_no, 2) = '-1'
AND NOT EXISTS
(
SELECT 1
FROM YourTable T2
WHERE LEFT(T2.seq_no, 8) = LEFT(T1.seq_no, 8)
AND T2.seq_no > T1.seq_no
);
Thanks
This would work if all sequence numbers were the same length. I should have mentioned this...apologies The sequence numbers can have between 3-5 digits in that middle segment, so your suggestions would not work in all cases. The first segment will always be 2 digits, then a '-' then the middle segment, between 3-5 digits, than another '-' then the last segment could be between 1-9999.