C#-规范化表[关闭]
Posted
技术标签:
【中文标题】C#-规范化表[关闭]【英文标题】:C#-normalizing a table [closed] 【发布时间】:2013-12-31 06:28:16 【问题描述】:我有一张这样的桌子:
我必须将其标准化为:
你能帮我写代码吗? 提前谢谢..
【问题讨论】:
什么代码?我没有看到任何... 【参考方案1】:查询:
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
【讨论】:
以上是关于C#-规范化表[关闭]的主要内容,如果未能解决你的问题,请参考以下文章