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;








1















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#?










share|improve this question


























  • 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

















1















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#?










share|improve this question


























  • 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













1












1








1


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#?










share|improve this question
















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-server






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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

















  • 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












1 Answer
1






active

oldest

votes


















5















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





share|improve this answer



























  • 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










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
);



);













draft saved

draft discarded


















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









5















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





share|improve this answer



























  • 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















5















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





share|improve this answer



























  • 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













5














5










5









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





share|improve this answer















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






share|improve this answer














share|improve this answer



share|improve this answer








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

















  • 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








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.



















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해