试试这个——
架构 -
DECLARE @SQL NVARCHAR(MAX)
IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL
DROP TABLE #temp
CREATE TABLE #temp
(
Num INT
, Name VARCHAR(10)
, [DayOfWeek] INT
, WeekNumber INT
, WeekLineNumber INT
)
INSERT INTO #temp (Num, Name, [DayOfWeek], WeekNumber, WeekLineNumber)
VALUES
(1, 'Test1', 1, 1, 1),
(2, 'Test2', 1, 1, 2),
(3, 'Test3', 2, 1, 1),
(4, 'Test4', 3, 2, 1)
使用 PIVOT 查询 -
DECLARE
@sel_cols VARCHAR(MAX)
, @cols VARCHAR(MAX)
SELECT @sel_cols = STUFF((
SELECT DISTINCT CHAR(13) + ', [Num' + CAST([DayOfWeek] AS VARCHAR(5)) + '] = ISNULL(MAX(CASE WHEN [DayOfWeek] = ' + CAST([DayOfWeek] AS VARCHAR(5)) + ' THEN CAST([Num' + CAST([DayOfWeek] AS VARCHAR(5)) + '] AS CHAR(2)) END), '''')'
+ CHAR(13) + ', [Name' + CAST([DayOfWeek] AS VARCHAR(5)) + '] = ISNULL(MAX(CASE WHEN [DayOfWeek] = ' + CAST([DayOfWeek] AS VARCHAR(5)) + ' THEN [Name' + CAST([DayOfWeek] AS VARCHAR(5)) + '] END), '''')'
FROM #temp
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 2, '')
PRINT @sel_cols
SELECT @cols = STUFF((
SELECT DISTINCT ', [_' + CAST([DayOfWeek] AS VARCHAR(5)) + ']'
FROM #temp
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 2, '')
SELECT @SQL = '
SELECT WeekNumber, ' + @sel_cols + '
FROM (
SELECT
*
, id = ''Name'' + CAST([DayOfWeek] AS VARCHAR(5))
, id2 = ''Num'' + CAST([DayOfWeek] AS VARCHAR(5))
FROM #temp t
) t3
PIVOT (
MAX(Name)
FOR id IN (' + REPLACE(@cols, '_', 'Name') + ')
) pivot1
PIVOT (
MAX(Num)
FOR id2 IN (' + REPLACE(@cols, '_', 'Num') + ')
) pivot2
GROUP BY WeekNumber, WeekLineNumber
ORDER BY WeekNumber
'
EXEC sys.sp_executesql @SQL
使用枚举查询 -
DECLARE
@WeekStart INT
, @WeekEnd INT
SELECT
@WeekStart = 1
, @WeekEnd = 7
SELECT @SQL = STUFF((
SELECT CHAR(13) + ', [Num' + num + '] = ISNULL(MAX(CASE WHEN [DayOfWeek] = ' + num + ' THEN CAST([Num] AS CHAR(2)) END), '''')'
+ CHAR(13) + ', [Name' + num + '] = ISNULL(MAX(CASE WHEN [DayOfWeek] = ' + num + ' THEN [Name] END), '''')'
FROM (
SELECT num = CAST(sv.number AS CHAR(1))
FROM [master].dbo.spt_values sv
WHERE sv.[type] = 'p'
AND sv.number BETWEEN @WeekStart AND @WeekEnd
) sv
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, 'SELECT
[WeekNumber]
,') + ' FROM #temp
GROUP BY WeekNumber, WeekLineNumber
ORDER BY WeekNumber'
EXEC sys.sp_executesql @SQL
输出 -
1. 枢轴
WeekNumber Num1 Name1 Num2 Name2 Num3 Name3
----------- ---- ---------- ---- ---------- ---- ----------
1 1 Test1 3 Test3
1 2 Test2
2 4 Test4
2.枚举
WeekNumber Num1 Name1 Num2 Name2 Num3 Name3 Num4 Name4 Num5 Name5 Num6 Name6 Num7 Name7
----------- ---- ---------- ---- ---------- ---- ---------- ---- ---------- ---- ---------- ---- ---------- ---- ----------
1 1 Test1 3 Test3
1 2 Test2
2 4 Test4