2016-12-14 96 views
-1

我有兩個表僱員主表和時間表表。如何從其他表中缺少的表中選擇記錄

員工表結構:

+------------+---------+ 
| emp_number | empname | 
+------------+---------+ 
|   2 | Jagdish | 
|   3 | Sulata | 
|   4 | Prasad | 
|   5 | Vijay | 
|   6 | Armin | 
+------------+---------+ 

和時間表表結構:

+------------+--------+------------+------------+ 
| emp_number | status | startDate | EndDate | 
+------------+--------+------------+------------+ 
|   2 | 0  | 2016-01-01 | 2016-01-07 | 
|   3 | 1  | 2016-02-01 | 2016-02-06 | 
|   4 | 40  | 2016-01-01 | 2016-01-07 | 
|   9 | 0  | 2016-01-06 | 2016-01-12 | 
|   10 | 4  | 2016-01-01 | 2016-01-08 | 
+------------+--------+------------+------------+ 

我們可以編寫一個查詢來獲取使用GROUP BY周所有員工記錄?
請引導我。謝謝。

+0

請分享預期輸出 – Wanderer

+0

你可以加入使用LEFT JOIN emp_number列兩個表。在where子句中,如果您選擇emp_number爲NULL條件,那麼您將缺少行 – Eralper

+0

我刪除了所有這些dbms標籤。隨意添加其中一個回來。 – jarlh

回答

0
SELECT * FROM Employee Table 
WHERE NOT EXISTS(SELECT 1 FROM Timesheet WHERE Employee.emp_number = Timesheet 
.emp_number AND Status IN (0,40)) 
0

下面的代碼嘗試按您的特定問題

select employee.* 
from employee 
where employee.emp_number not in (select emp_number from timesheet) 
and timesheet.status in (0,40) and timesheet.enddate between '2016-01-01' 
and '2016-01-07' 
0

我相信這是正確的代碼:

SELECT * 
FROM Timesheet INNER JOIN Employee ON Timesheet.emp_number=Employee.emp_number 
WHERE (Employee.status = 0 OR Employee.status = 40) 
    AND (Timesheet.startDate = '2016-01-01' AND Timesheet.EndDate = '2016-01-07') 

您可能需要更改分號之間的日期取決於關於startDate和EndDate的數據類型,

例如:'2016-01-01 00:00:00'

+0

沒有它沒有工作。我認爲左連接將起作用而不是內連接。但我沒有得到增加額外的狀態和日期條件的地方。 – Madhura

0

- 試試這個代碼。它的速度更快

WITH cte_timesheet AS (
    select employee_id, 
     MAX(CASE WHEN status IN (0,40) THEN 1 ELSE 0 END) include_status 
    from em_timesheet 
    where start_date = '2016-12-05' 
     AND end_date = '2016-12-11' 
    GROUP BY employee_id 
) 
SELECT emp_number, 
     empname 
    FROM em_employee e 
    LEFT JOIN cte_timesheet t ON t.employee_id = e.emp_number 
    WHERE t.employee_id IS NULL 
    OR t.include_status = 1 
0

試試這個下面code.its很簡單

select * from #emp E 
LEFT JOIN #TimeSheet T ON t.emp_nbr=e.emp_nbr 
where startdate>='2016-01-01' and enddate<='2016-01-07' 
and status_ in(0,40) 
相關問題