我有一个查询,此查询显示将基于当天所显示的那一天的当天。
在此时间表中,我的开始日期和结束日期从2014-01-06 2014-01-12一周开始..
例如:
declare @Hours as Table ( EmpId Int, Monday Time, Tuesday Time, Wednesday Time,
Thursday Time, Friday Time, Saturday Time, Sunday Time, StartDate Date, EndDate Date );
insert into @Hours
( EmpId, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, StartDate, EndDate )
values
( 1, '08:00', '00:00', '00:00', '00:00', '00:00', '00:00', '00:00', '2014-01-06 00:00:00.000', '2014-01-12 00:00:00.000' );
select * from @Hours;
with Week as (
-- Build a table of all of the dates in the work week.
select StartDate as WorkDate, EndDate
from @Hours
union all
select DateAdd( day, 1, WorkDate ), EndDate
from Week
where WorkDate < EndDate ),
DaysHours as (
-- Build a table of the hours assigned to each date.
select EmpId,
case DatePart( weekday, W.WorkDate )
when 1 then H.Monday
when 2 then H.Tuesday
when 3 then H.Wednesday
when 4 then H.Thursday
when 5 then H.Friday
when 6 then H.Saturday
when 7 then H.Sunday
end as Hours,
WorkDate as StartDate, WorkDate as EndDate
from Week as W inner join
@Hours as H on H.StartDate <= W.WorkDate and W.WorkDate <= H.EndDate )
-- Output the non-zero hours.
select EmpId, Hours,StartDate as StartDate, EndDate
from DaysHours
where Hours <> Cast( '00:00' as Time );
需要像这样的输出:
EmpId Hours StartDate EndDate
----------- ---------------- ---------- ----------
1 08:00:00.0000000 2014-01-06 2014-01-06
因为星期一我们只有值。但我的输出就像这样
EmpId Hours StartDate EndDate
----------- ---------------- ---------- ----------
1 08:00:00.0000000 2014-01-12 2014-01-12
它应该根据价值在哪一天起作用。
任何正文都可以在此查询中自行更改。
谢谢,
答案 0 :(得分:0)
执行后
EmpId Hours StartDate EndDate
1 08:00:00.0000000 2014-01-06 2014-01-06
MS SQL Server 2008 R2
答案 1 :(得分:0)
尝试此查询:
SELECT x.EmpId, ca.Hours, ca.CurrentDate AS StartDate, ca.CurrentDate AS EndDate
FROM @Hours x
CROSS APPLY
(
SELECT y.Hours, DATEADD(DAY, y.NumOfDays, x.StartDate)
FROM
(
SELECT x.Monday, 0
UNION ALL SELECT x.Tuesday, 1
UNION ALL SELECT x.Wednesday, 2
UNION ALL SELECT x.Thursday, 3
UNION ALL SELECT x.Friday, 4
UNION ALL SELECT x.Saturday, 5
UNION ALL SELECT x.Sunday, 6
) y (Hours, NumOfDays)
WHERE y.Hours <> '00:00:00.0000000'
) ca (Hours, CurrentDate);