C# - 对表进行规范化

时间:2013-12-31 06:28:16

标签: sql sql-server tsql sql-server-ce

我有这样一张桌子: enter image description here

我必须将其标准化为: enter image description here

请您帮我解释一下代码..? 事先提前......

1 个答案:

答案 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