我在SQL Sever中有一列数据,需要将其扩展为多个(2)列。
原始数据如下:
Col1
-------
Monday
Jon
Boris
Natalie
Tuesday
James
Tom
Boris
我希望它看起来像这样:
Name | Day
-------+---------
Jon | Monday
Boris | Monday
Natalie| Monday
James | Tuesday
Tom | Tuesday
Boris | Tuesday
非常感谢提前。
答案 0 :(得分:4)
假设您将能够将该标识列添加到源表进行排序,并且您的表格看起来像这样:
CREATE TABLE Table1 (id int identity(1,1), Col1 NVARCHAR(50))
INSERT INTO Table1 (Col1)
VALUES
('Monday'),('Jon'),('Boris'),('Natalie'),
('Tuesday'),('James'),('Tom'),('Boris')
您可以尝试以下操作:
。
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)
答案 1 :(得分:2)
试试这个 -
<强>查询:强>
DECLARE @temp TABLE (Col1 NVARCHAR(50))
INSERT INTO @temp (Col1)
VALUES
('Monday'),('Jon'),('Boris'),('Natalie'),
('Tuesday'),('James'),('Tom'),('Boris')
;WITH cte AS
(
SELECT
Col1
, rn = ROW_NUMBER() OVER (ORDER BY 1/0) % 4
, rn2 = ROW_NUMBER() OVER (ORDER BY 1/0)
FROM @temp
)
SELECT
[Day] = t.Col1
, Name = t2.Col1
FROM cte t
OUTER APPLY (
SELECT *
FROM cte t2
WHERE t2.rn2 BETWEEN t.rn2 + 1 AND t.rn2 + 3
) t2
WHERE t.rn = 1
<强>输出:强>