我有一个如下表,我需要按周(系统日期)分组
tran_date Hours Tech_ID Tech_Name
02/02/2019 16:30 1 310091 Nasser Ahmed Muhammad
02/02/2019 17:30 8 310094 Ajish Babu Parambath
03/02/2019 08:30 8 310380 Nishad Mulayath Mohanan
04/02/2019 08:30 8 310380 Nishad Mulayath Mohanan
04/02/2019 08:30 8 310094 Ajish Babu Parambath
05/02/2019 08:30 1 310091 Nasser Ahmed Muhammad
06/02/2019 08:30 1 310380 Nishad Mulayath Mohanan
06/02/2019 08:30 5 310094 Ajish Babu Parambath
09/02/2019 09:30 3 310091 Nasser Ahmed Muhammad
09/02/2019 09:30 3 310094 Ajish Babu Parambath
09/02/2019 11:00 1 310380 Nishad Mulayath Mohanan
09/02/2019 13:30 1 310380 Nishad Mulayath Mohanan
09/02/2019 13:30 1 310091 Nasser Ahmed Muhammad
09/02/2019 14:30 1 310094 Ajish Babu Parambath
09/02/2019 16:30 2 310094 Ajish Babu Parambath
10/02/2019 08:30 1 310094 Ajish Babu Parambath
10/02/2019 08:30 2 310380 Nishad Mulayath Mohanan
10/02/2019 09:30 1 310094 Ajish Babu Parambath
10/02/2019 10:30 2 310091 Nasser Ahmed Muhammad
10/02/2019 13:30 1 310380 Nishad Mulayath Mohanan
10/02/2019 13:30 2 310094 Ajish Babu Parambath
10/02/2019 14:30 1 310380 Nishad Mulayath Mohanan
10/02/2019 15:30 1 310094 Ajish Babu Parambath
10/02/2019 16:30 1 310094 Ajish Babu Parambath
13/02/2019 08:30 4 310380 Nishad Mulayath Mohanan
14/02/2019 13:30 1 310091 Nasser Ahmed Muhammad
14/02/2019 14:30 0.5 310091 Nasser Ahmed Muhammad
我期望得到如下所示的结果。
tran_week Total
2/1/2019 - 2/7/2019 40
2/8/2019 - 2/14/2019 29.5
答案 0 :(得分:0)
只需尝试此代码
=> /aaa
=> /bbb
=> /ccc
答案 1 :(得分:0)
您可以尝试以下操作。
;with cte as
(
select cast(tran_date as date) tran_date, Hours
from @mytable
)
SELECT Convert(varchar, WS, 101) + '-' + Convert(varchar, WE, 101) AS trans_week ,SUM(HOURS) Total FROM
(
SELECT DATEADD(dd, -(DATEPART(dw, tran_date)-1), tran_date) WS, DATEADD(dd, 7-(DATEPART(dw, tran_date)), tran_date) WE
, Hours
FROM cte
)
T
GROUP BY WS,WE
order by ws
注意:如果您想更改一周的第一天,则需要像下面这样先进行设置。
SET DATEFIRST 6
答案 2 :(得分:0)
如果您通过选择的编程语言生成查询的select部分的字符串,则以下代码将起作用,因此将能够计算小时数:
select
sum (case when t.tran_date between range1_1 and range1_2 then t.hours else 0 end) as range1,
sum (case when t.tran_date between range2_1 and range2_2 then t.hours else 0 end) as range2,
sum (case when t.tran_date between range3_1 and range3_2 then t.hours else 0 end) as range3,
sum (case when t.tran_date between range3_1 and range4_2 then t.hours else 0 end) as range4,
...
from your_table as t