我需要一些帮助才能以这种格式转换数据:
Owner WeekStart Total
04206C26-347A-4984-BAD4-4C812D6035A4 07/07/2014 495
04206C26-347A-4984-BAD4-4C812D6035A4 14/07/2014 650
04206C26-347A-4984-BAD4-4C812D6035A4 21/07/2014 454
06454465-9E7A-4385-8B5F-3436F0B0983E 07/07/2014 160
06454465-9E7A-4385-8B5F-3436F0B0983E 14/07/2014 492
06454465-9E7A-4385-8B5F-3436F0B0983E 21/07/2014 448
这样的事情:
Owner 07/07/2014 14/07/2014 21/07/2014
04206C26-347A-4984-BAD4-4C812D6035A4 495 650 454
06454465-9E7A-4385-8B5F-3436F0B0983E 160 492 448
我认为可能使用枢轴但我找不到解决方案。我正在使用SQL Server 2008。
答案 0 :(得分:1)
此查询应解决您的问题:
declare @table table(Owner uniqueidentifier, WeekStart varchar(30), Total int)
INSERT INTO @table(Owner,WeekStart,Total) VALUES( '04206C26-347A-4984-BAD4-4C812D6035A4', '07/07/2014', 495)
INSERT INTO @table(Owner,WeekStart,Total) VALUES( '04206C26-347A-4984-BAD4-4C812D6035A4', '14/07/2014', 650)
INSERT INTO @table(Owner,WeekStart,Total) VALUES( '04206C26-347A-4984-BAD4-4C812D6035A4', '21/07/2014', 454)
INSERT INTO @table(Owner,WeekStart,Total) VALUES( '06454465-9E7A-4385-8B5F-3436F0B0983E', '07/07/2014', 160)
INSERT INTO @table(Owner,WeekStart,Total) VALUES( '06454465-9E7A-4385-8B5F-3436F0B0983E', '14/07/2014', 492)
INSERT INTO @table(Owner,WeekStart,Total) VALUES( '06454465-9E7A-4385-8B5F-3436F0B0983E', '21/07/2014', 448)
select * from @table
SELECT Owner, [07/07/2014], [14/07/2014], [21/07/2014]
FROM
(SELECT Owner, WeekStart, Total
FROM @table) AS SourceTable
PIVOT
(
AVG(Total)
FOR WeekStart IN ([07/07/2014], [14/07/2014], [21/07/2014])
) AS PivotTable
order by Owner;
要查看此查询的执行结果,请参阅此SQL Fiddle。