24.9. Folding a List of Numbers

It is possible to use the Sequence table to give columns in the same row, which are related to each other, values with a little math instead of self-joins.

For example, given the numbers 1 to (n), you might want to spread them out across (k) columns. Let (k = 3) so we can see the pattern.

SELECT seq_nbr,
       CASE WHEN MOD((seq_nbr + 1), 3) = 2
                 AND seq_nbr + 1 <= :n
            THEN (seq_nbr + 1)
            ELSE NULL END AS second,
       CASE WHEN MOD((seq_nbr + 2), 3) = 0
                 AND (seq_nbr + 2) <= :n
            THEN (seq_nbr + 2)
            ELSE NULL END AS third
  FROM Sequence
 WHERE MOD((seq_nbr + 3), 3) = 1
  AND seq_nbr <= :n;

Columns which have no value assigned to them will get a NULL. That is, for (n = 8) the incomplete row will be (7, 8, NULL) and for (n = 7) it would ...

Get Joe Celko's SQL for Smarties, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.