Sql Query用于创建具有时差的出勤报告

时间:2017-03-02 16:31:31

标签: sql-server-2008 report

我正在处理一份应该反映以下输出的出勤报告 - 员工出勤时间和延迟时间的计数:

Department - OnTime - Late - Late_1_To_10_Mins
1 - 2 - 1 - 1
2 - 2 - 1 - 1

现在,我已经使用了以下几乎可以工作但却重复数据的查询:

SELECT DISTINCT Department,
CASE WHEN
CONVERT(VARCHAR(5), InTime, 108)   = '10:00' THEN
(SELECT COUNT(PersonID) FROM Persons WHERE
CONVERT(VARCHAR(5), InTime, 108)   = '10:00') ELSE 0 END AS OnTime,
CASE WHEN
CONVERT(VARCHAR(5), InTime, 108)   > '10:00' THEN
(SELECT COUNT(PersonID) FROM Persons WHERE
CONVERT(VARCHAR(5), InTime, 108)   > '10:00') ELSE 0 END AS Late 
FROM Persons

输出如下:

Department - OnTime - Late
1 - 0 - 2
1 - 4 - 0
2 - 0 - 2
2 - 4 - 0

注意:我不确定如何在1到10分钟之间获取数据,并从表格的InTime列中找出数据。上面的查询至少应该让我适当地看到OnTimeLate数据,但似乎错过了一些东西。下面是表格结构及其示例数据:

 CREATE TABLE [Persons] (
    [PersonID] [int] NULL ,
    [InTime] [datetime] NULL ,
    [OutTime] [datetime] NULL ,
    [Department] [int] NULL 
) ON [PRIMARY]
GO

INSERT INTO Persons(PersonID,  InTime,  OutTime,  Department)VALUES (1001, '2017-03-02 10:00:11.297', '2017-03-02 06:00:11.293', 1)
INSERT INTO Persons(PersonID,  InTime,  OutTime,  Department)VALUES (1002, ' 2017-03-02 10:00:08.180', ' 2017-03-02 06:00:10.293', 1)
INSERT INTO Persons(PersonID,  InTime,  OutTime,  Department)VALUES (1003, ' 2017-03-02 10:01:08.240', ' 2017-03-02 06:00:12.220', 1)
INSERT INTO Persons(PersonID,  InTime,  OutTime,  Department)VALUES (1004, ' 2017-03-02 10:02:20.200', ' 2017-03-02 06:00:20.200', 2)
INSERT INTO Persons(PersonID,  InTime,  OutTime,  Department)VALUES (1005, ' 2017-03-02 10:02:20.240', ' 2017-03-02 06:00:22.200', 2)
INSERT INTO Persons(PersonID,  InTime,  OutTime,  Department)VALUES (1006, ' 2017-03-02 10:04:20.100', ' 2017-03-02 06:00:20.320', 2)

1 个答案:

答案 0 :(得分:2)

对于使用条件聚合的给定示例数据:

select 
    department
  , OnTime = sum(case when convert(time,InTime) <  '10:01:00' then 1 else 0 end)
  , Late   = sum(case when convert(time,InTime) >= '10:01:00' then 1 else 0 end)
  , Late_1_To_10_Mins = sum(case 
        when convert(time,InTime) >= '10:01:00' 
         and convert(time,InTime) <  '10:11:00'
          then 1 else 0 end)
from persons
group by department

返回:

+------------+--------+------+--------------+
| department | OnTime | Late | Late_10_Mins |
+------------+--------+------+--------------+
|          1 |      2 |    1 |            1 |
|          2 |      0 |    3 |            3 |
+------------+--------+------+--------------+

测试设置:here