如下使用sum(case...
将数据作为列跨天旋转(或查看PIVOT
运算符)。此外,请考虑多年可能会如何影响您的结果,并相应地调整分组。
set dateformat dmy;
set datefirst 1; --monday
declare @YourTable table (Id int, Value int, ondate datetime)
insert into @YourTable
select 1, 10, '06/05/2013' union all
select 2, 9, '07/05/2013' union all
select 3, 5, '08/05/2013' union all
select 4, 89, '09/05/2013' union all
select 5, 8, '10/05/2013' union all
select 6, 23, '11/05/2013' union all
select 7, 3, '12/05/2013' union all
select 8, 5, '13/05/2013' union all
select 9, 8, '14/05/2013'
select [mo]=sum(case when datename(weekday, ondate) = 'Monday' then Value else 0 end),
[tu]=sum(case when datename(weekday, ondate) = 'Tuesday' then Value else 0 end),
[we]=sum(case when datename(weekday, ondate) = 'Wednesday' then Value else 0 end),
[th]=sum(case when datename(weekday, ondate) = 'Thursday' then Value else 0 end),
[fr]=sum(case when datename(weekday, ondate) = 'Friday' then Value else 0 end),
[sa]=sum(case when datename(weekday, ondate) = 'Saturday' then Value else 0 end),
[su]=sum(case when datename(weekday, ondate) = 'Sunday' then Value else 0 end)
from @YourTable
where ondate between '06/05/2013' and '14/05/2013'
group
by datepart(week, ondate);
-- Result:
/*
mo tu we th fr sa su
10 9 5 89 8 23 3
5 8 0 0 0 0 0
*/