0

我有一个查询和数据,需要从中生成时间表。

我当前的查询如下:

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 和 line date 的时间分解为 15 分钟。

像这样的东西:

code1 | code2 | line_date | 0900worked | 0915worked | 0930worked |

其中的值0900workedTF

--

编辑

我需要按 code1 和 line_date 对周期进行分组。因此,在上面的示例中,10450962013/09/25. 我需要两个会话出现在同一行并计算所有期间。

4

3 回答 3

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]
,       ...
于 2013-09-27T12:00:45.420 回答
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

SQL小提琴

于 2013-09-27T12:29:23.017 回答
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 语句。

于 2013-09-27T12:11:51.537 回答