慕哥9229398
为了将数据转换为您想要的结果,您需要同时使用UNPIVOT和PIVOT函数。该UNPIVOT函数接受A和B列并将结果转换为行。然后,您将使用该PIVOT函数将day值转换为列:select *from(
select day, col, value from yourtable unpivot
(
value for col in (A, B)
) unpiv) srcpivot(
max(value)
for day in (Mon, Tue, Wed, Thu, Fri)) piv请参阅SQL Fiddle with Demo。如果您使用的是SQL Server 2008+,则可以使用CROSS APPLYwith VALUES来取消数据的移动。您的代码将更改为以下内容:select *from(
select day, col, value from yourtable cross apply
(
values ('A', A),('B', B)
) c (col, value)) srcpivot(
max(value)
for day in (Mon, Tue, Wed, Thu, Fri)) piv请参阅SQL Fiddle with Demo。编辑#1,将您当前的查询应用到上述解决方案中,您将使用类似于此的内容:select *from(
select LEFT(datename(dw,datetime),3) as DateWeek,
col,
value from DataTable
cross apply
(
values ('A', ACalls), ('B', BCalls)
) c (col, value)) srcpivot(
sum(value)
for dateweek in (Mon, Tue, Wed, Thu, Fri)) piv