2017-03-02 56 views
1

我與出席報告應體現以下輸出工作出席報告 - 員工出勤的時間,晚計數:SQL查詢來創建使用時間差

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) 

回答

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 | 
+------------+--------+------+--------------+ 

測試設置:http://rextester.com/NRQ26806

+0

由於@SqlZim。幾乎工作。你能詳細說明爲什麼你使用過這個 - 「OnTime = sum(convert(time,InTime)時的情況'''10:01:00'then 1 else 0 end')我的意思是** SUM **和1 else 0在最後? –

+1

這就是讓我們根據您在問題中描述的條件進行聚合。或者你可以使用'coalesce(count(轉換時間,InTime)''10:01:00'然後1結束),0)' – SqlZim

+1

@ AT-2016爲什麼你說'幾乎成功'? – SqlZim