我有一个查询和数据,我需要从中生成时间表。
我目前的查询如下:
SELECT contract.lect_code code1,
contract.coll_code code2,
line_date,
start_time,
end_time,
DATEPART(DW,line_date) AS day_number,
datename (dw,line_date) AS nameofday,
convert(varchar(8),start_time,108) AS start_time2,
convert(varchar(8),end_time,108) AS end_time2
FROM bk_line
INNER JOIN contract ON contract.contract_no = bk_line.contract_no
WHERE line_date BETWEEN '2013/09/23' AND '2013/09/27'
AND coll_code = 'TEL01'
AND bk_line_status = 'CE'
--And lect_code = 10430973
这为我提供了以下格式的数据:
我需要一种方法,将每个code1和行日期的时间分解为15分钟。
这样的事情:
code1 | code2 | line_date | 0900worked | 0915worked | 0930worked |
0900worked
中的值为T
或F
。
-
修改
我需要按照code1和line_date对句点进行分组。因此,在上面的示例中,1045096
在2013/09/25
上进行了两次会话。我需要两个会话出现在同一行,计算所有期间。
答案 0 :(得分:2)
select case
when convert(varchar(8),end_time,108) >= '09:15:00'
and convert(varchar(8),start_time,108) <= '09:00:00'
then 'T'
else 'F'
end as [0900worked]
, case
when convert(varchar(8),end_time,108) >= '09:30:00'
and convert(varchar(8),start_time,108) <= '09:15:00'
then 'T'
else 'F'
end as [0915worked]
, ...
答案 1 :(得分:1)
你可以这样做,但我认为有更好的方法来检查是否有人在给定的时间间隔内工作!
with "nums"
as
(
select 1 as "value"
union all select "value" + 15 as "value"
from "nums"
where "value" <= 95*15
)
, "intervals"
as
(
select
"id" = "value" / 15
, "startDate" = dateadd( minute, "value" -1 , dateadd(year, datediff(year, 0, getdate()), 0))
, "endDate" = dateadd( minute, "value" + 14, dateadd( year, datediff( year, 0, getdate()), 0 ))
from
"nums"
)
,"matched"
as
(
select
I.*
, D."id" as "code1"
from
intervals as I
left join "data" as D
on D."startDate" <= I."startDate"
and D."endDate" >= I."endDate"
)
select
*
from
(
select
"code1"
, "startDate"
from
"matched"
) as Data
pivot( count(Data."startdate")
for "startDate"
in ( "2013-01-01 00:00:00.000"
, "2013-01-01 00:15:00.000"
, "2013-01-01 00:30:00.000"
, "2013-01-01 00:45:00.000"
, "2013-01-01 01:00:00.000"
, "2013-01-01 01:15:00.000"
, "2013-01-01 01:30:00.000"
, "2013-01-01 01:45:00.000"
, "2013-01-01 02:00:00.000"
, "2013-01-01 02:15:00.000"
, "2013-01-01 02:30:00.000"
)) as p
where p.code1 is not null
答案 2 :(得分:0)
也许使用以下内容创建一个间隔表:
;with t as
(
select cast('00:00:00' as time) as intStart,
0 as l
union all
select DATEADD(MINUTE, 15,intStart),
l+1
from t
where intStart<='23:30:00'
)
select *
from t;
然后,您可以使用它来加入您的数据,并提供范围以查看白天的任何15分钟间隔。
然后,您可以针对任何间隔使用Andomar的select语句。