MSSQL使用列将多行转换为一行

时间:2016-11-22 19:47:05

标签: sql sql-server

我需要转换,转置,无论正确的术语是多行的数据集,而是返回包含多列的单行。以下是我用

开头的数据示例
EID               PM             Project     HOURS    WeekStarting
joe@test.com      tom@test.com   Proj A       6         11/28/2016
joe@test.com      tom@test.com   Proj A       3         12/5/2016
joe@test.com      tom@test.com   Proj A       7         12/12/2016
joe@test.com      tom@test.com   Proj A       3         12/19/2016
sue@test.com      sam@test.com   Proj B       3         11/28/2016
sue@test.com      sam@test.com   Proj B       6         12/12/2016
sue@test.com      sam@test.com   Proj B       7         12/19/2016

我想像这样格式化数据

EID            PM             Project    Week1  Week2 Week3  Week4 
joe@test.com   tom@test.com   Proj A       6     3      7      3
sue@test.com   sam@test.com   Proj B       3     0      6      7

请注意,对于sue,我的源数据在第2周没有数据,因此第2周的结果为0。

目前我正在使用reduce函数在Javascript中执行此操作,但它非常混乱。我宁愿尝试修复数据并使用干净的Javascript。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

Declare @SQL varchar(max)
Select  @SQL = Stuff((Select ','+QuoteName('Week'+cast(WeekNr as varchar(25)))
                       From  (Select Distinct Top 100 Percent WeekNr=Dense_Rank() over (Order By WeekStarting) From YourTable 
                       Order By 1) A
                       For XML Path ('')),1,1,'')

Select  @SQL = 'Select EID,PM,Project,' + @SQL + ' 
                From (
                        Select EID
                              ,PM
                              ,Project
                              ,Item = ''Week''+cast(Dense_Rank() over (Order By WeekStarting) as varchar(25))
                              ,Val  = Hours
                         From  YourTable
                     ) A
                Pivot (max(Val) For Item in (' + @SQL + ') ) p'

Exec(@SQL);

返回

enter image description here

答案 1 :(得分:0)

您可以这样查询:

;with cte as (
select *, DATEPART(WEEK, weekstarting)  -
    DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,weekstarting), 0)) + 1 AS WEEK_OF_MONTH
from yourtranspose
)
select Eid, PM, Project, [1], [2], [3], [4], [5] from
( select EID, PM, Project, WEEK_OF_MONTH , hours from cte ) a
pivot (max(hours) for week_of_month in ([1], [2], [3], [4], [5])) p

答案 2 :(得分:-2)

对于每个额外的行,您需要将表连接到自身