我试图获得本周的以下输出 -
Full Name | Mon | Tue | Wed | Thu | Fri | Sat | Sun
Peter Smith | 09:00 - 12:00 | NULL | 08:30 - 13:00 | NULL | NULL | NULL | 10:00 - 12:13
Peter Smith | 13:00 - 17:00 | NULL | 14:30 - 16:00 | NULL | NULL | NULL | 13:00 - 17:14
Paul Stevens | 09:00 - 12:00 | NULL | 08:30 - 13:00 | NULL | NULL | NULL | 10:00 - 12:13
这是在日志中显示时钟,从表中拉出 -
**ClockInLogs**
ID - INT
UserID - INT
ClockDateTimeIn - DateTime
ClockDateTimeOut - DateTime
Status - INT (ClockedIn/ClockedOut)
来源数据 -
ID | UserID | ClockDateTimeIn | ClockDateTimeOut | Status
1 | 10000 | 2013-07-30 13:40:39.913 | 2013-07-30 13:42:20.113 | 0
2 | 10000 | 2013-07-30 14:13:10.947 | 2013-07-30 14:25:15.570 | 0
3 | 10001 | 2013-07-30 14:13:52.817 | 2013-07-30 14:25:19.063 | 0
从名为Users的联接表中提取全名。
我是如何获得所需输出的?我知道我需要做一个PIVOT但是无法弄清楚如何在细胞内显示时间。
谢谢!
答案 0 :(得分:2)
declare @test table (ID int, UserID int, ClockDateTimeIn datetime, ClockDateTimeOut datetime, [Status] bit)
declare @user table (ID int, Name nvarchar(128))
insert into @test
select 1, 10000, '2013-07-30 13:40:39.913', '2013-07-30 13:42:20.113', 0 union all
select 2, 10000, '2013-07-30 14:13:10.947', '2013-07-30 14:25:15.570', 0 union all
select 3, 10001, '2013-07-30 14:13:52.817', '2013-07-30 14:25:19.063', 0 union all
select 3, 10001, '2013-07-29 10:13:52.817', '2013-07-30 18:25:19.063', 0
insert into @user
select 10000, 'Martin Smith' union all
select 10001, 'Paul Stevens'
;with CTE as
(
select
u.Name,
left(datename(weekday, t.ClockDateTimeIn), 3) as Col,
convert(nvarchar(5), t.ClockDateTimeIn, 108) + ' - ' + convert(nvarchar(5), t.ClockDateTimeOut, 108) as Value,
row_number() over (partition by u.Name, datename(weekday, t.ClockDateTimeIn) order by t.ClockDateTimeIn) as ID
from @test as t
left outer join @user as u on u.ID = t.UserID
)
select P.*
from CTE as C
pivot
(
min(Value) for Col in ([Mon], [Tue], [Wen], [Thu], [Fri], [Sat], [Sun])
) as P
order by Name, ID