我有两个表员工主表和时间表。
员工表格结构:
+------------+---------+
| 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 |
+------------+--------+------------+------------+
我们可以编写一个查询来按周使用分组来获取所有员工的记录吗? 请指导我。谢谢。
答案 0 :(得分:0)
SELECT * FROM Employee Table
WHERE NOT EXISTS(SELECT 1 FROM Timesheet WHERE Employee.emp_number = Timesheet
.emp_number AND Status IN (0,40))
答案 1 :(得分: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'
答案 2 :(得分: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'
答案 3 :(得分: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
答案 4 :(得分:0)
尝试以下代码。非常简单
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)