我必须将其标准化为:
请您帮我解释一下代码..? 事先提前......
答案 0 :(得分:2)
<强>查询:强>
IF OBJECT_ID('tempdb.dbo.#temp') IS NOT NULL
DROP TABLE #temp
GO
CREATE TABLE #temp (
SomeColumn CHAR(1),
[30-12-2013] INT,
[31-12-2013] INT,
[01-01-2014] INT
)
INSERT INTO #temp (SomeColumn, [30-12-2013], [31-12-2013], [01-01-2014])
VALUES
('A', 540, 100, 246),
('B', 130, 90, 377)
SELECT *
FROM #temp
UNPIVOT (
[Date] FOR Amount IN ([30-12-2013], [31-12-2013], [01-01-2014])
) unpvt
<强>输出:强>
SomeColumn Date Amount
---------- ----------- -----------
A 540 30-12-2013
A 100 31-12-2013
A 246 01-01-2014
B 130 30-12-2013
B 90 31-12-2013
B 377 01-01-2014
其他信息:
Is UNPIVOT the best way for converting columns into rows?
动态解决方案:
IF OBJECT_ID('dbo.temp') IS NOT NULL
DROP TABLE temp
GO
CREATE TABLE temp (
SomeColumn CHAR(1),
[30-12-2013] INT,
[31-12-2013] INT,
[01-01-2014] INT
)
INSERT INTO dbo.temp (SomeColumn, [30-12-2013], [31-12-2013], [01-01-2014])
VALUES
('A', 540, 100, 246),
('B', 130, 90, 377)
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = 'SELECT *
FROM dbo.temp
UNPIVOT (
[Date] FOR Amount IN (' + STUFF((
SELECT ', [' + name + ']'
FROM sys.columns
WHERE [object_id] = OBJECT_ID('dbo.temp')
AND name LIKE '__-__-____'
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')
) unpvt'
PRINT @SQL
EXEC sys.sp_executesql @SQL
<强>输出:强>
SELECT *
FROM dbo.temp
UNPIVOT (
[Date] FOR Amount IN ([30-12-2013], [31-12-2013], [01-01-2014])
) unpvt