2

我有一个程序让用户选择一个日期范围,然后它查询 SQL 服务器数据库以检索他们使用小时数的日期。我想将日期放在自己的列中,而不是全部放在同一个列中。例如:

Employee   Total Hours  Monday 3/10  Tuesday 3/11 ....
Doe, John    40             8             8

这是现在的查询:

SELECT e.emp_fullname, t.tc_hours, t.punchDate 
FROM WaspTime.dbo.vEmployeeInfo as e, WaspTime.dbo.vTimeCards as t 
WHERE e.emp_id = t.tc_emp 
AND t.punchDate >= '03/10/2013'
AND t.punchDate <= '03/20/2013'

这是结果:

Smith, Dan  8  2013-03-10 00:00:00.000
Smith, Dan  8 2013-03-11 00:00:00.000   
4

1 回答 1

1

像这样的事情,无论你有多少时期都会重复。

我假设你会:

  • 需要SUM(或COUNT?)您的工作时间?
  • 使用某种@period_start_date参数,然后将每个周期偏移一天、2 天、3 天等...

在文本编辑器中手工完成,所以请原谅拼写错误,或者如果事情只是简单地不起作用 - 但我认为这个想法是清晰/合理的。

CREATE PROCEDURE GetHoursWorkedInPeriod @periodStartDate datetime = getdate() AS
SELECT 
e.emp_fullname, 
sum(t1.tc_hours) as 'Day1Hours', 
min(t1.punchDate) as 'Day1Date'.

sum(t2.tc_hours) as 'Day2Hours', 
min(t2.punchDate) as 'Day2Date',

sum(t3.tc_hours) as 'Day3Hours', 
min(t3.punchDate) as 'Day3Date',

...and so on

FROM 
WaspTime.dbo.vEmployeeInfo as e

inner join WaspTime.dbo.vTimeCards as t1
on e.emp_id = t1.tc_emp 
AND t1.punchDate >= DATEADD (day , 0 , @periodStartDate )
AND t1.punchDate < DATEADD (day , 1 , @periodStartDate )

inner join WaspTime.dbo.vTimeCards as t2
on e.emp_id = t2.tc_emp 
AND t2.punchDate >= DATEADD (day , 1 , @periodStartDate )
AND t2.punchDate < DATEADD (day , 2 , @periodStartDate )

inner join WaspTime.dbo.vTimeCards as t3
on e.emp_id = t3.tc_emp 
AND t3.punchDate >= DATEADD (day , 2 , @periodStartDate )
AND t3.punchDate < DATEADD (day , 3 , @periodStartDate )

...and so on.

GROUP BY
e.emp_fullname

编辑以根据 OP 的要求将每个时间段限制为一天,并且还明确包括在结果集中应用小时数的日期。

于 2013-03-22T16:11:39.227 回答