使用如下所示的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
*/
使用CTE和數據透視 – MaxRecursion 2013-05-06 06:25:58
@AnilDiggiwal:你嘗試過什麼? – 2013-05-06 06:27:37