0

我试图获得本周的以下输出 -

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

全名是从名为用户的连接表中提取的。

任何想法如何获得所需的输出?我知道我需要做一个 PIVOT,但不知道如何在单元格中显示时间。

谢谢!

4

1 回答 1

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

SQL 提琴示例

于 2013-07-30T14:01:25.300 回答