I have a single column of data in SQL Sever and need to expand this to multiple (2) columns.
The raw data looks like so:
Col1
-------
Monday
Jon
Boris
Natalie
Tuesday
James
Tom
Boris
I'd like it to look like this:
Name | Day
-------+---------
Jon | Monday
Boris | Monday
Natalie| Monday
James | Tuesday
Tom | Tuesday
Boris | Tuesday
Many thanks in advance.
Assuming you are going to be able to add that identity column to source table for ordering and that your table will look something like this:
CREATE TABLE Table1 (id int identity(1,1), Col1 NVARCHAR(50))
INSERT INTO Table1 (Col1)
VALUES
('Monday'),('Jon'),('Boris'),('Natalie'),
('Tuesday'),('James'),('Tom'),('Boris')
You can try the following:
.
CREATE TABLE #weekDays (wd NVARCHAR(10));
INSERT INTO #weekDays
VALUES
('Monday'), ('Tuesday'), ('Wednesday'),
('Thursday'), ('Friday'), ('Saturday'), ('Sunday');
WITH CTE_Days AS
(
SELECT t.*
FROM Table1 t
INNER JOIN #weekDays wd ON wd.wd = t.col1
)
SELECT *
FROM CTE_Days d1
INNER JOIN Table1 t ON t.id > d1.id AND t.id <
COALESCE((
SELECT MIN(d2.id)
FROM CTE_Days d2
WHERE d2.id > d1.id
), t.id + 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With