我有一个像这样设置的表
Project Category Date Hours
Proj1 test 8/2/2010 2
Proj1 test 8/3/2010 8
Proj1 test 8/4/2010 4
Proj1 test 8/5/2010 3
Proj1 test 8/6/2010 5
我想开发一个查询,您可以输入星期六(周结束日期)并获得这样的结果
WeekEnding Project Category SunHrs MonHrs TuesHrs WedHrs ThuHrs FriHrs SatHrs
8/7/2010 Proj1 test 0 2 8 4 3 5 0
谢谢
答案 0 :(得分:3)
一些好文章可以提供帮助:
答案 1 :(得分:1)
这是一种方式。它看起来很像kludgey,但是那时的枢轴总是看起来像那样。
DECLARE @Saturday datetime
SET @Saturday = 'Aug 7, 2010'
SELECT
@Saturday WeekEnding
,Project
,Category
,isnull([1], 0) SunHrs
,isnull([2], 0) MonHrs
,isnull([3], 0) TueHrs
,isnull([4], 0) WedHrs
,isnull([5], 0) ThuHrs
,isnull([6], 0) FriHrs
,isnull([7], 0) SatHrs
from (select Project, Category, Datepart(dw, Date) DOW, Hours
from MyTable
-- Fixed bug from -7 to -6
where Date between dateadd(dd, /*-7*/ -6, @Saturday) and @Saturday) Source
pivot (max(Hours)
for DOW in ([1],[2],[3],[4],[5],[6],[7]) ) as pvt
我使用以下内容设置数据来测试:
DROP TABLE MyTable
CREATE TABLE MyTable
(
Project varchar(10) not null
,Category varchar(10) not null
,Date datetime not null
,Hours int not null
)
INSERT MyTable
values
('Proj1', 'test', '8/2/2010', 2 ),
('Proj1', 'test', '8/3/2010', 8 ),
('Proj1', 'test', '8/4/2010', 4 ),
('Proj1', 'test', '8/5/2010', 3 ),
('Proj1', 'test', '8/6/2010', 5 )