sql server - Combine single ids into range
I have a table that contains lots of integers. This table gets queried and the results end up being turned into xml. If the table contains for example the following items:
SELECT itemId FROM items WHERE enabled = true
1
2
3
5
The my final xml output after some processing would be:
<item id="1" />
<item id="2" />
<item id="3" />
<item id="5" />
The xml ends up being fairly large and alot of the items are actually ranges. What I would like to do is update my query to combine ranges (alot of these items are 'neighbours' so the xml generated would be quite a bit smaller). I'm trying to get the procedures results to be more like this:
1-3
5
So that the final XML 开发者_如何学Golooks something like this (if I can just change the procedure, the XML processing can stay the same):
<item id="1-3"/>
<item id="5"/>
I was thinking my best route may be to use a self join where table1.itemId = table2.itemId - 1
but I haven't been able to get it working. Does anyone have any suggestions on how I can go about this?
Would this help?
SELECT
MIN(ItemID)
,MAX(ItemID)
FROM
(
SELECT ItemID, RANK() OVER (ORDER BY ItemID) R FROM Items
) Tmp
GROUP BY
ItemID - R
I'd think this should do the trick: 1) order by itemID 2) use OVER...PARTITION to get row number 3) use it in a recursive Common Table Expression that joins a number to all others where anchor + row number equals the ItemID, thereby finding all sequential numbers 4) group by the anchor in an outer query and then use MIN and MAX to get the range.
精彩评论