Convert sequential numbers into single column with missing values in SQLAdd a column with a default value to an existing table in SQL ServerHow to check if a column exists in a SQL Server table?How to concatenate text from multiple rows into a single text string in SQL server?Inserting multiple rows in a single SQL query?Select n random rows from SQL Server tableHow do I escape a single quote in SQL Server?Finding duplicate values in a SQL tableFind all tables containing column with specified name - MS SQL ServerSQL select only rows with max value on a columnBest practices for SQL varchar column length
Why does this London Underground poster from 1924 have a Star of David atop a Christmas tree?
How did medieval manors handle population growth? Was there room for more fields to be ploughed?
Where does the last newline character come from in this sed's result?
Inspiration for failed idea?
SVO airport, how to avoid scam taxis without pre-booking?
Pen test results for web application include a file from a forbidden directory that is not even used or referenced
Is there a word or phrase that means "use other people's wifi or Internet service without consent"?
Principal payments
Can I lend a small amount of my own money to a bank at the federal funds rate?
What is the difference between ?int $number and int $number = null?
Fantasy Macro Economics: What would Merfolk trade for?
Is Nikon D500 a good fit for nature and ambient-lighting portraits and occasional other uses?
How do you say "half the time …, the other half …" in German?
What is the sound/audio equivalent of "unsightly"?
How can I reply to coworkers who accuse me of automating people out of work?
Journal published a paper, ignoring my objections as a referee
Printing a list as "a, b, c." using Python
Should I use the words "pyromancy" and "necromancy" even if they don't mean what people think they do?
Why can't I identify major and minor chords?
Group riding etiquette
Why does Sauron not permit his followers to use his name?
Does Dovescape counter Enchantment Creatures?
Answer with an image of my favorite musician
Can a network vulnerability be exploited locally?
Convert sequential numbers into single column with missing values in SQL
Add a column with a default value to an existing table in SQL ServerHow to check if a column exists in a SQL Server table?How to concatenate text from multiple rows into a single text string in SQL server?Inserting multiple rows in a single SQL query?Select n random rows from SQL Server tableHow do I escape a single quote in SQL Server?Finding duplicate values in a SQL tableFind all tables containing column with specified name - MS SQL ServerSQL select only rows with max value on a columnBest practices for SQL varchar column length
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have a list of sample ids for a site in the format of:
Sitename, Sample Number such that there is n number of sample numbers for a given site. For example, the data could be:
site1 | 1
site1 | 2
etc to an arbitrary n.
Using the following as a similar example, this data below would get the answer from the last select statement:
CREATE TABLE #SiteWithId(SiteId VARCHAR(50), SampleNumber INT)
INSERT INTO #SiteWithId
(
SiteId,
SampleNumber
)
values
( 'test', -- SiteId - varchar(50)
1 -- SampleNumber - int
),
('test',2),
('test',3),
('test',4),
('test',6),
('test',7)
SELECT * FROM #SiteWithId
DROP TABLE #SiteWithId
--the answer
SELECT 'test', '1-4,6-7'
Note, that the missing item creates a break in the final answer.
I know I can loop through the dataset in C# and create such an item. But does anyone know to create such a value using only sql so I can just spit out the needed values for the report? I think I could do a loop in sql too but I am scared it would be unscalable since that is not really what sql is made to do.
Is there a better way to do this other than a loop in sql or c#?
sql
add a comment |
I have a list of sample ids for a site in the format of:
Sitename, Sample Number such that there is n number of sample numbers for a given site. For example, the data could be:
site1 | 1
site1 | 2
etc to an arbitrary n.
Using the following as a similar example, this data below would get the answer from the last select statement:
CREATE TABLE #SiteWithId(SiteId VARCHAR(50), SampleNumber INT)
INSERT INTO #SiteWithId
(
SiteId,
SampleNumber
)
values
( 'test', -- SiteId - varchar(50)
1 -- SampleNumber - int
),
('test',2),
('test',3),
('test',4),
('test',6),
('test',7)
SELECT * FROM #SiteWithId
DROP TABLE #SiteWithId
--the answer
SELECT 'test', '1-4,6-7'
Note, that the missing item creates a break in the final answer.
I know I can loop through the dataset in C# and create such an item. But does anyone know to create such a value using only sql so I can just spit out the needed values for the report? I think I could do a loop in sql too but I am scared it would be unscalable since that is not really what sql is made to do.
Is there a better way to do this other than a loop in sql or c#?
sql
No need for loops. This seems to be a rather small task using a Numbers/Tally table (or even an ad-hoc Tally Table). HOWEVER, I don't understand how your data is structured. Stings ? Rows? Some formatting would be helpful.
– John Cappelletti
Mar 27 at 22:17
add a comment |
I have a list of sample ids for a site in the format of:
Sitename, Sample Number such that there is n number of sample numbers for a given site. For example, the data could be:
site1 | 1
site1 | 2
etc to an arbitrary n.
Using the following as a similar example, this data below would get the answer from the last select statement:
CREATE TABLE #SiteWithId(SiteId VARCHAR(50), SampleNumber INT)
INSERT INTO #SiteWithId
(
SiteId,
SampleNumber
)
values
( 'test', -- SiteId - varchar(50)
1 -- SampleNumber - int
),
('test',2),
('test',3),
('test',4),
('test',6),
('test',7)
SELECT * FROM #SiteWithId
DROP TABLE #SiteWithId
--the answer
SELECT 'test', '1-4,6-7'
Note, that the missing item creates a break in the final answer.
I know I can loop through the dataset in C# and create such an item. But does anyone know to create such a value using only sql so I can just spit out the needed values for the report? I think I could do a loop in sql too but I am scared it would be unscalable since that is not really what sql is made to do.
Is there a better way to do this other than a loop in sql or c#?
sql
I have a list of sample ids for a site in the format of:
Sitename, Sample Number such that there is n number of sample numbers for a given site. For example, the data could be:
site1 | 1
site1 | 2
etc to an arbitrary n.
Using the following as a similar example, this data below would get the answer from the last select statement:
CREATE TABLE #SiteWithId(SiteId VARCHAR(50), SampleNumber INT)
INSERT INTO #SiteWithId
(
SiteId,
SampleNumber
)
values
( 'test', -- SiteId - varchar(50)
1 -- SampleNumber - int
),
('test',2),
('test',3),
('test',4),
('test',6),
('test',7)
SELECT * FROM #SiteWithId
DROP TABLE #SiteWithId
--the answer
SELECT 'test', '1-4,6-7'
Note, that the missing item creates a break in the final answer.
I know I can loop through the dataset in C# and create such an item. But does anyone know to create such a value using only sql so I can just spit out the needed values for the report? I think I could do a loop in sql too but I am scared it would be unscalable since that is not really what sql is made to do.
Is there a better way to do this other than a loop in sql or c#?
sql
sql
edited Mar 27 at 23:06
done_merson
asked Mar 27 at 22:02
done_mersondone_merson
1,2121 gold badge15 silver badges25 bronze badges
1,2121 gold badge15 silver badges25 bronze badges
No need for loops. This seems to be a rather small task using a Numbers/Tally table (or even an ad-hoc Tally Table). HOWEVER, I don't understand how your data is structured. Stings ? Rows? Some formatting would be helpful.
– John Cappelletti
Mar 27 at 22:17
add a comment |
No need for loops. This seems to be a rather small task using a Numbers/Tally table (or even an ad-hoc Tally Table). HOWEVER, I don't understand how your data is structured. Stings ? Rows? Some formatting would be helpful.
– John Cappelletti
Mar 27 at 22:17
No need for loops. This seems to be a rather small task using a Numbers/Tally table (or even an ad-hoc Tally Table). HOWEVER, I don't understand how your data is structured. Stings ? Rows? Some formatting would be helpful.
– John Cappelletti
Mar 27 at 22:17
No need for loops. This seems to be a rather small task using a Numbers/Tally table (or even an ad-hoc Tally Table). HOWEVER, I don't understand how your data is structured. Stings ? Rows? Some formatting would be helpful.
– John Cappelletti
Mar 27 at 22:17
add a comment |
1 Answer
1
active
oldest
votes
Here is a solution that relies on window functions. The difference between the SampleNumber of a record and its ROW_NUMBER() within groups of records having the same SiteName gives you the group it belongs to. Then, the outer query aggregates each group:
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
Demo on DB Fiddle:
Sample data:
SiteName | SampleNumber
:------- | -----------:
site1 | 1
site1 | 2
site1 | 3
site1 | 5
site1 | 6
site1 | 8
site1 | 9
site1 | 10
Results:
SiteName | SampleRange
:------- | :----------
site1 | 1-3
site1 | 5-6
site1 | 8-10
If you want all the ranges of each site concatenated in one record, you can add another level of aggregation and use STRING_AGG() (available since SQL Server 2017):
SELECT SiteName, STRING_AGG(SampleRange,',') SampleRange
FROM (
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
) y
GROUP BY SiteName
Demo:
SiteName | SampleRange
:------- | :-----------
site1 | 1-3,5-6,8-10
Thank you this is very helpful. This is very close to what I need. Is there any way to return those 3 rows concatenated into 1 row?
– done_merson
Mar 28 at 21:33
1
@done_merson: welcome! Answer updated.
– GMB
Mar 28 at 21:42
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387151%2fconvert-sequential-numbers-into-single-column-with-missing-values-in-sql%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is a solution that relies on window functions. The difference between the SampleNumber of a record and its ROW_NUMBER() within groups of records having the same SiteName gives you the group it belongs to. Then, the outer query aggregates each group:
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
Demo on DB Fiddle:
Sample data:
SiteName | SampleNumber
:------- | -----------:
site1 | 1
site1 | 2
site1 | 3
site1 | 5
site1 | 6
site1 | 8
site1 | 9
site1 | 10
Results:
SiteName | SampleRange
:------- | :----------
site1 | 1-3
site1 | 5-6
site1 | 8-10
If you want all the ranges of each site concatenated in one record, you can add another level of aggregation and use STRING_AGG() (available since SQL Server 2017):
SELECT SiteName, STRING_AGG(SampleRange,',') SampleRange
FROM (
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
) y
GROUP BY SiteName
Demo:
SiteName | SampleRange
:------- | :-----------
site1 | 1-3,5-6,8-10
Thank you this is very helpful. This is very close to what I need. Is there any way to return those 3 rows concatenated into 1 row?
– done_merson
Mar 28 at 21:33
1
@done_merson: welcome! Answer updated.
– GMB
Mar 28 at 21:42
add a comment |
Here is a solution that relies on window functions. The difference between the SampleNumber of a record and its ROW_NUMBER() within groups of records having the same SiteName gives you the group it belongs to. Then, the outer query aggregates each group:
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
Demo on DB Fiddle:
Sample data:
SiteName | SampleNumber
:------- | -----------:
site1 | 1
site1 | 2
site1 | 3
site1 | 5
site1 | 6
site1 | 8
site1 | 9
site1 | 10
Results:
SiteName | SampleRange
:------- | :----------
site1 | 1-3
site1 | 5-6
site1 | 8-10
If you want all the ranges of each site concatenated in one record, you can add another level of aggregation and use STRING_AGG() (available since SQL Server 2017):
SELECT SiteName, STRING_AGG(SampleRange,',') SampleRange
FROM (
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
) y
GROUP BY SiteName
Demo:
SiteName | SampleRange
:------- | :-----------
site1 | 1-3,5-6,8-10
Thank you this is very helpful. This is very close to what I need. Is there any way to return those 3 rows concatenated into 1 row?
– done_merson
Mar 28 at 21:33
1
@done_merson: welcome! Answer updated.
– GMB
Mar 28 at 21:42
add a comment |
Here is a solution that relies on window functions. The difference between the SampleNumber of a record and its ROW_NUMBER() within groups of records having the same SiteName gives you the group it belongs to. Then, the outer query aggregates each group:
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
Demo on DB Fiddle:
Sample data:
SiteName | SampleNumber
:------- | -----------:
site1 | 1
site1 | 2
site1 | 3
site1 | 5
site1 | 6
site1 | 8
site1 | 9
site1 | 10
Results:
SiteName | SampleRange
:------- | :----------
site1 | 1-3
site1 | 5-6
site1 | 8-10
If you want all the ranges of each site concatenated in one record, you can add another level of aggregation and use STRING_AGG() (available since SQL Server 2017):
SELECT SiteName, STRING_AGG(SampleRange,',') SampleRange
FROM (
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
) y
GROUP BY SiteName
Demo:
SiteName | SampleRange
:------- | :-----------
site1 | 1-3,5-6,8-10
Here is a solution that relies on window functions. The difference between the SampleNumber of a record and its ROW_NUMBER() within groups of records having the same SiteName gives you the group it belongs to. Then, the outer query aggregates each group:
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
Demo on DB Fiddle:
Sample data:
SiteName | SampleNumber
:------- | -----------:
site1 | 1
site1 | 2
site1 | 3
site1 | 5
site1 | 6
site1 | 8
site1 | 9
site1 | 10
Results:
SiteName | SampleRange
:------- | :----------
site1 | 1-3
site1 | 5-6
site1 | 8-10
If you want all the ranges of each site concatenated in one record, you can add another level of aggregation and use STRING_AGG() (available since SQL Server 2017):
SELECT SiteName, STRING_AGG(SampleRange,',') SampleRange
FROM (
SELECT SiteName, CONCAT(MIN(SampleNumber), '-', MAX(SampleNumber)) SampleRange
FROM (
SELECT
SiteName,
SampleNumber,
ROW_NUMBER() OVER(PARTITION BY SiteName ORDER BY SampleNumber) rn
FROM mytable
) x
GROUP BY SiteName, (SampleNumber - rn)
) y
GROUP BY SiteName
Demo:
SiteName | SampleRange
:------- | :-----------
site1 | 1-3,5-6,8-10
edited Mar 28 at 21:42
answered Mar 27 at 22:24
GMBGMB
22.3k6 gold badges11 silver badges28 bronze badges
22.3k6 gold badges11 silver badges28 bronze badges
Thank you this is very helpful. This is very close to what I need. Is there any way to return those 3 rows concatenated into 1 row?
– done_merson
Mar 28 at 21:33
1
@done_merson: welcome! Answer updated.
– GMB
Mar 28 at 21:42
add a comment |
Thank you this is very helpful. This is very close to what I need. Is there any way to return those 3 rows concatenated into 1 row?
– done_merson
Mar 28 at 21:33
1
@done_merson: welcome! Answer updated.
– GMB
Mar 28 at 21:42
Thank you this is very helpful. This is very close to what I need. Is there any way to return those 3 rows concatenated into 1 row?
– done_merson
Mar 28 at 21:33
Thank you this is very helpful. This is very close to what I need. Is there any way to return those 3 rows concatenated into 1 row?
– done_merson
Mar 28 at 21:33
1
1
@done_merson: welcome! Answer updated.
– GMB
Mar 28 at 21:42
@done_merson: welcome! Answer updated.
– GMB
Mar 28 at 21:42
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387151%2fconvert-sequential-numbers-into-single-column-with-missing-values-in-sql%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
No need for loops. This seems to be a rather small task using a Numbers/Tally table (or even an ad-hoc Tally Table). HOWEVER, I don't understand how your data is structured. Stings ? Rows? Some formatting would be helpful.
– John Cappelletti
Mar 27 at 22:17