Hello,
With your current SORT card, after the 'INREC IFTHEN' operation, the data changes to (I've rearranged the OVERLAY column from 168 to 60):
HD HEADER 1234567
LN TRAILER 1111 1111
LN TRAILER 3333 3333
LN TRAILER 5555 5555
LN TRAILER 4444 4444
LN TRAILER 2222 2222
HD HEADER 2345678 2222
LN TRAILER 2111 2111
LN TRAILER 2333 2333
LN TRAILER 2555 2555
LN TRAILER 2444 2444
LN TRAILER 2221 2221
Since you do not have an identifier to GROUP your HEADER record, the second header is actually treated a part of the GROUP - LN, which is immediately before the second HEADER record. Which is why you have '2222' instead of 4 bytes of space when the second HEADER is encountered.
LN TRAILER 4444 4444
LN TRAILER 2222 2222 ---> Clean OVERLAY
HD HEADER 2345678 2222 --> Since GROUP remains same, hence OVERLAYd value
LN TRAILER 2111 2111
Now when you perform a SORT on the OVERLAY'd 4 bytes of data, with EQUALS, it changes to (EQUALS simply shuffles the order of the two '2222' group records):
HD HEADER 1234567
LN TRAILER 1111 1111
LN TRAILER 2111 2111
LN TRAILER 2221 2221
LN TRAILER 2222 2222
HD HEADER 2345678 2222
LN TRAILER 2333 2333
LN TRAILER 2444 2444
LN TRAILER 2555 2555
LN TRAILER 3333 3333
LN TRAILER 4444 4444
LN TRAILER 5555 5555
One of the multiple possible solutions would be GROUPing on the basis of HEADER, and padding the detail records individually:
*
* GROUP THE DATA ON THE BASIS OF HEADER RECORD, AND PAD THE HEADER VALUE
* TO EACH RECORD OF THIS GROUP; THIS HELPS IN UNIQUELY IDENTIFYING THE
* RECORDS AT THE TIME OF SORTING.
*
INREC IFTHEN=(WHEN=GROUP,BEGIN=(1,2,CH,EQ,C'HD'),PUSH=(81:11,7)),
*
* PAD THE DETAIL RECORDS WITH 4 BYTES OF IDENTIFIER FOR EACH RECORD.
*
IFTHEN=(WHEN=(1,2,CH,EQ,C'LN'),OVERLAY=(88:12,4))
*
* SORT THE DATA ON THE BASIS OF EXTENDED RECORD'S VALUE.
*
SORT FIELDS=(81,11,CH,A)
*
* REMOVE THE PADDED DATA.
*
OUTFIL REMOVECC,BUILD=(1,80)
Gives:
HD HEADER 1234567
LN TRAILER 1111
LN TRAILER 2222
LN TRAILER 3333
LN TRAILER 4444
LN TRAILER 5555
HD HEADER 2345678
LN TRAILER 2111
LN TRAILER 2221
LN TRAILER 2333
LN TRAILER 2444
LN TRAILER 2555