我有这张桌子:
Reg_No Student_Name Subject Total
----------- -------------------- ----------- -----------
101 Canday 85 347
94
78
90
102 Andy 75 332
88
91
78
我想要这张桌子
Reg_No Student_Name Subject1 Subject2 Subject3 Subject4 Total
----------- -------------------- ----------- ----------- ----------- ----------- -----------
101 Canday 85 94 78 90 347
102 Andy 75 88 91 78 332
答案 0 :(得分:0)
请考虑您的表名为#Temp
。我在查询中编写了逻辑。
;WITH CTE AS
(
-- Get ROW_NUMBER() in default order of your table
SELECT *,ROW_NUMBER()OVER(ORDER BY (SELECT(0)))RNO
FROM #TEMP
)
,CTE2 AS
(
-- Since we need some logic to get the NULL VALUES for each Id we fill REG_NO where previous REG_NO is not null
-- Note that Id must be in ascending order in your table as in question
SELECT RNO, (SELECT TOP 1 Reg_No FROM CTE WHERE RNO<=C1.RNO AND Reg_No IS NOT NULL ORDER BY Reg_No DESC) REGNO,
Student_Name,[SUBJECT],[TOTAL]
FROM CTE C1
)
,CTE3 AS
(
-- Get all Student_Name and Total where those are NULL
SELECT N1.RNO,N1.REGNO,
n1.Student_Name,N2.[Subject],N1.Total
FROM CTE2 N1
LEFT JOIN CTE2 N2 ON N1.REGNO=N2.REGNO AND N1.Student_Name IS NOT NULL
WHERE n1.Student_Name IS NOT NULL AND N2.[Subject] IS NOT NULL
)
SELECT RNO,REGNO,Student_Name,[Subject],
-- To get columns names for Pivot ie Subject1,Subject2 etc
'Subject' + CAST(ROW_NUMBER() OVER(PARTITION BY REGNO ORDER BY (SELECT(0)))AS VARCHAR(10)) COLS
INTO #NEWTABLE
FROM CTE3
UNION ALL
SELECT DISTINCT RNO,REGNO,Student_Name,[TOTAL],'Total'
FROM CTE3
获取用于旋转的列
DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + COLS + ']',
'[' + COLS + ']')
FROM (SELECT DISTINCT COLS FROM #NEWTABLE) PV
ORDER BY COLS
现在转动它
DECLARE @query NVARCHAR(MAX)
SET @query = '
SELECT * FROM
(
SELECT REGNO REG_NO,Student_Name,[Subject],COLS FROM #NEWTABLE
) x
PIVOT
(
SUM([Subject])
FOR [COLS] IN (' + @cols + ')
) p
ORDER BY REG_NO
'
EXEC SP_EXECUTESQL @query
<强> RESULT 强>