我在SQL Server 2012中有一个数据表,如下所示。我想要做的是查询数据,但重组布局。有一列名为' factor'包含7-8个不同的标签,这些标签具有相应的值(值列)。我想要的是将列中的因素作为列 - 请参阅所需的输出部分以了解我的意思。编写查询以查看我的数据的最佳方法是什么?
所需的输出
pdate abc def ghi
1-1-13 1 3 2
2-1-13 1 3 2
表格示例
factor pdate value
abc 1-1-13 1
def 1-1-13 3
ghi 1-1-13 2
abc 2-1-13 1
def 2-1-13 3
ghi 2-1-13 2
abc 3-1-13 1
def 3-1-13 3
ghi 3-1-13 2
abc 4-1-13 1
def 4-1-13 3
ghi 4-1-13 2
答案 0 :(得分:2)
正如outisnihil所提到的更好的方法是使用PIVOT
使用PiVOT
SELECT pdate
, [abc]
, [def]
, [ghi]
FROM YOUR_table
PIVOT(SUM([value]) FOR factor IN (
[abc]
, [def]
, [ghi]
)) AS val
使用CASE
...
您可以使用每个因子值的大小写在输出中生成新列。
SELECT pdate
, CASE
WHEN factor = 'abc' SUM(value) END abc
, CASE
WHEN factor = 'def' SUM(value) END def
, CASE
WHEN factor = 'ghi' SUM(value) END ghi
FROM YOUR_table GROUP BY pdate
答案 1 :(得分:2)
动态版本,如果您不想对[因子]值进行硬编码...
If Object_ID('tempdb..#factorDateValues') Is Not Null Drop Table #factorDateValues
Create Table #factorDateValues (factor Varchar(50), pdate Date, value Int)
Insert #factorDateValues (factor, pdate, value)
Values ('abc','2013-01-01', 1),
('def','2013-01-01', 3),
('ghi','2013-01-01', 2),
('abc','2013-02-01', 1),
('def','2013-02-01', 3),
('ghi','2013-02-01', 2),
('abc','2013-03-01', 1),
('def','2013-03-01', 3),
('ghi','2013-03-01', 2),
('abc','2013-04-01', 1),
('def','2013-04-01', 3),
('ghi','2013-04-01', 2)
Declare @sql Nvarchar(Max)
Select @sql = Coalesce(@sql + ',','') + '[' + factor + ']'
From #factorDateValues
Group By factor
Order By factor
Set @sql = 'Select pDate,' + @sql +
'From #factorDateValues
Pivot (Max([value]) For factor In (' + @sql + ')) As val'
Exec sp_executeSQL @sql