Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically create ranges from numeric sequences
    primarykey
    data
    text
    <p>I have a table like the following:</p> <pre><code>+----+-----+-----+ | ID | GRP | NR | +----+-----+-----+ | 1 | 1 | 101 | | 2 | 1 | 102 | | 3 | 1 | 103 | | 4 | 1 | 105 | | 5 | 1-2 | 106 | | 6 | 1-2 | 109 | | 7 | 1-2 | 110 | | 8 | 2 | 201 | | 9 | 2 | 202 | | 10 | 3 | 300 | | 11 | 3 | 350 | | 12 | 3 | 351 | | 13 | 3 | 352 | +----+-----+-----+ </code></pre> <p>I wanted to create a view which groups this list by <code>GRP</code> and concatenates values in <code>NR</code>. Is it possible to dynamically detect sequences and shorten them into ranges? Like <code>1, 2, 3, 5</code> would become <code>1-3, 5</code>.</p> <p>So the result should look like this:</p> <pre><code>+-----+--------------------+ | GRP | NRS | +-----+--------------------+ | 1 | 101 - 103, 105 | | 1-2 | 106, 109 - 110 | | 2 | 201 - 202 | | 3 | 300, 350 - 352 | +-----+--------------------+ </code></pre> <p>What i got now is simply concatenate values, so the table above would become this:</p> <pre><code>+-----+--------------------+ | GRP | NRS | +-----+--------------------+ | 1 | 101, 102, 103, 105 | | 1-2 | 106, 109, 110 | | 2 | 201, 202 | | 3 | 300, 350, 351, 352 | +-----+--------------------+ </code></pre> <p>Here's the actual statement:</p> <pre><code>DECLARE @T TABLE ( ID INT IDENTITY(1, 1) , GRP VARCHAR(10) , NR INT ) INSERT INTO @T VALUES ('1',101),('1',102),('1',103),('1',105) ,('1-2',106),('1-2',109), ('1-2',110) ,('2',201),('2',202) ,('3',300),('3',350),('3',351),('3',352) SELECT * FROM @T ;WITH GROUPNUMS (RN, GRP, NR, NRS) AS ( SELECT 1, GRP, MIN(NR), CAST(MIN(NR) AS VARCHAR(MAX)) FROM @T GROUP BY GRP UNION ALL SELECT CT.RN + 1, T.GRP, T.NR, CT.NRS + ', ' + CAST(T.NR AS VARCHAR(MAX)) FROM @T T INNER JOIN GROUPNUMS CT ON CT.GRP = T.GRP WHERE T.NR &gt; CT.NR ) SELECT NRS.GRP, NRS.NRS FROM GROUPNUMS NRS INNER JOIN ( SELECT GRP, MAX(RN) AS MRN FROM GROUPNUMS GROUP BY GRP ) R ON NRS.RN = R.MRN AND NRS.GRP = R.GRP ORDER BY NRS.GRP </code></pre> <p>Can anyone tell me if it's easily possible to do something like that? Would be great if anyone has an idea and would like to share it.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload