我正在使用SQL Server 2008 R2。
我有一个与标题和详细信息表相关的SQL查询问题。我有一个标题表,我在那里存储位置和放大器部门和WEEK_START_DATE开始。我有一个详细信息表,我在那里存储employee_id& job_code& work_date&小时。
我想找到那些位于不同标题中并且具有相同week_start_date但位置和/或部门不同的员工。
以下是解释:
我有一个标题表:
CREATE TABLE header (
header_id bigint not null PRIMARY KEY,
location_code int not null,
department_code int not null,
week_start_date datetime not null )
我有一个详细信息表:
CREATE TABLE detail (
detail_id bigint not null PRIMARY KEY,
header_id bigint not null FOREIGN KEY header(header_id),
employee_id int not null,
job_code int not null,
work_date datetime not null,
hours decimal(8,2) not null )
标头表的唯一键为location_code + department_code + week_start_date。
例如,这是标题表中的数据:
header_id = 11,location_code = 22,department_code = 33, WEEK_START_DATE开始=' 2016年2月8日'
header_id = 12,location_code = 22,department_code = 39, WEEK_START_DATE开始=' 2016年2月8日'
header_id = 13,location_code = 22,department_code = 33, WEEK_START_DATE开始=' 2016年2月15日'
header_id = 14,location_code = 21,department_code = 33, WEEK_START_DATE开始=' 2016年2月8日'
标题表格中的每一行都可以在详细信息表格中包含多行。
详细信息表具有唯一键,如header_id + employee_id + job_code + work_date。
例如,这是1000598 employee_id的详细信息表中的数据:
detail_id = 101,header_id = 11,employee_id = 1000598,job_code = 77, work_date =' 2016-02-08',hours = 5.00
detail_id = 102,header_id = 11,employee_id = 1000598,job_code = 77, work_date =' 2016-02-09',hours = 4.00
detail_id = 109,header_id = 12,employee_id = 1000598,job_code = 79, work_date =' 2016-02-11',hours = 4.50
例如,这是1000599 employee_id的详细信息表中的数据:
detail_id = 121,header_id = 11,employee_id = 1000599,job_code = 78, work_date =' 2016-02-10',hours = 8.00
detail_id = 122,header_id = 14,employee_id = 1000599,job_code = 75, work_date =' 2016-02-12',hours = 3.00
例如,这是1000600 employee_id的详细信息表中的数据:
detail_id = 131,header_id = 11,employee_id = 1000600,job_code = 72, work_date =' 2016-02-11',hours = 7.00
detail_id = 132,header_id = 13,employee_id = 1000600,job_code = 75, work_date =' 2016-02-17',hours = 3.00
SQL查询应返回1000598 employee_id,因为1000598具有department_code = 33和department_code = 39的数据,因为相同的week_start_date =' 2016-02-08'。
SQL查询应返回1000599 employee_id,因为1000599具有相同week_start_date =' 2016-02-08'的location_code = 22和location_code = 21的数据。
SQL查询不应返回1000600 employee_id。
这是我提出的开始:
select
h.employee_id,
d.week_start_date
from
header h (nolock)
inner join detail d (nolock)
on h.header_id = d.header_id
group by
h.employee_id,
d.week_start_date
order by
1,
2
不多。
答案 0 :(得分:3)
我想找到那些处于不同标题中的员工 week_start_date但位置和/或部门不同。
以下查询将返回超过1 (employee_id, week_start_date)
或location_code
department_code
对
select d.employee_id, h.week_start_date
from detail d
join header h on h.header_id = d.header_id
group by d.employee_id, h.week_start_date -- employees with same week_start_date
having (
count(distinct h.location_code) > 1 -- have more than 1 location
or count(distinct h.department_code) > 1 -- or more than 1 department
)