WITH t AS ( SELECT 'KEY1' id, 1 no UNION ALL SELECT 'KEY2' , 1 UNION ALL SELECT 'KEY3' , 1 UNION ALL SELECT 'KEY4' , 1 UNION ALL SELECT 'KEY5' , 1 UNION ALL SELECT 'KEY6' , 2 UNION ALL SELECT 'KEY7' , 2 UNION ALL SELECT 'KEY8' , 2 UNION ALL SELECT 'KEY9' , 2 UNION ALL SELECT 'KEY10', 3 UNION ALL SELECT 'KEY11', 3 UNION ALL SELECT 'KEY12', 3 UNION ALL SELECT 'KEY13', 3 UNION ALL SELECT 'KEY14', 3 UNION ALL SELECT 'KEY15', 3 UNION ALL SELECT 'KEY16', 4 UNION ALL SELECT 'KEY17', 4 UNION ALL SELECT 'KEY18', 4 UNION ALL SELECT 'KEY19', 5 UNION ALL SELECT 'KEY20', 5 ) , tmp AS ( SELECT no , 1 rn , CEILING(COUNT(*) / 5.) * 5 max_rn FROM t GROUP BY no UNION ALL SELECT no , rn + 1 rn , max_rn FROM tmp WHERE rn + 1 <= max_rn ) SELECT b.id , a.no FROM tmp a LEFT OUTER JOIN (SELECT id, no , ROW_NUMBER() OVER(PARTITION BY no ORDER BY id) rn FROM t ) b ON a.no = b.no AND a.rn = b.rn ORDER BY a.no, a.rn ;
WITH t AS ( SELECT 'KEY1' id, 1 no UNION ALL SELECT 'KEY2' , 1 UNION ALL SELECT 'KEY3' , 1 UNION ALL SELECT 'KEY4' , 1 UNION ALL SELECT 'KEY5' , 1 UNION ALL SELECT 'KEY6' , 2 UNION ALL SELECT 'KEY7' , 2 UNION ALL SELECT 'KEY8' , 2 UNION ALL SELECT 'KEY9' , 2 UNION ALL SELECT 'KEY10', 3 UNION ALL SELECT 'KEY11', 3 UNION ALL SELECT 'KEY12', 3 UNION ALL SELECT 'KEY13', 3 UNION ALL SELECT 'KEY14', 3 UNION ALL SELECT 'KEY15', 3 UNION ALL SELECT 'KEY16', 4 UNION ALL SELECT 'KEY17', 4 UNION ALL SELECT 'KEY18', 4 UNION ALL SELECT 'KEY19', 5 UNION ALL SELECT 'KEY20', 5 ) , tmp AS ( SELECT id, no , rn , CASE rn WHEN cnt THEN CEILING(cnt / 5.) * 5 ELSE rn END max_rn FROM (SELECT id, no , ROW_NUMBER() OVER(PARTITION BY no ORDER BY id) rn , COUNT(*) OVER(PARTITION BY no) cnt FROM t ) a UNION ALL SELECT null id , no , rn + 1 rn , max_rn FROM tmp WHERE rn + 1 <= max_rn ) SELECT id, no FROM tmp ORDER BY no, rn ;