sql服务器按周总和分组
我有下面的代码,时间表。 下面是时间表列
下面是用户表列 用户名,名字,姓氏
下面是时间表的记录
timeid,shiftdate,starttime,endtime,userid
1,1st Jun 2019,1:00,10:00,1
2,2st Jun 2019,1:00,10:00,2
3,3rd Jun 2019,4:00,11:00,1
10,11th Jun 2019,4:00,11:00,1
14,11th Jun 2019,4:00,11:00,1
19,11th Jun 2019,4:00,11:00,1
我的问题是我想生成每周总报告 像下面这样
Userid | 3rd June to 9th June | 10th to 16 June
1 10 20
2 5 5
我尝试了以下代码
select sum(datediff(hour,startdate,enddate),userid,shiftdate from time
group by userid,shiftdate
我每天都在给我关于用户的信息。但是我需要 我要在每周的第一天到每周的最后一天之间有小时数。
我每天都在给我关于用户的信息。但是我需要 我需要在每周的第一天到每周的最后一天之间有小时数。 你能帮忙吗
答案 0 :(得分:0)
这可能会帮助
DECLARE @TimeTable TABLE(
timeid INT,shiftdate DATETIME ,starttime TIME,endtime TIME ,userid INT
)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(1,'1 Jun 2019','1:00','10:00',1)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(2,'2 Jun 2019','1:00','10:00',2)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(2,'3 Jun 2019','1:00','10:00',2)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(3,'3 Jun 2019','4:00','11:00',1)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(10,'11 Jun 2019','4:00','11:00',1)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(14,'11 Jun 2019','4:00','11:00',3)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(19,'11 Jun 2019','4:00','11:00',3)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(2,'11 Jun 2019','1:00','10:00',2)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(10,'19 Jun 2019','4:00','11:00',1)
INSERT INTO @TimeTable(timeid,shiftdate,starttime,endtime,userid) VALUES(10,'20 Jun 2019','4:00','11:00',1)
;WITH WeeklyTotal
AS(
SELECT *
,DATEDIFF(HOUR,starttime,endtime) totalHours
,DATEPART(WEEK, shiftdate) - DATEPART(WEEK, DATEADD(MM, DATEDIFF(MM,0,shiftdate), 0))+ 1 AS weekOfMonth
FROM @TimeTable
)
SELECT * FROM (
SELECT userid,weekOfMonth,totalHours
FROM WeeklyTotal
) aaa
pivot
(
SUM(totalHours)
for weekOfMonth in ([1], [2], [3],[4],[5],[6])
) piv;