我正在使用SQL Server 2008 R2。如何解決這個SQL查詢(標題和詳細信息)?
我有一個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年2月8日」,小時= 5.00
detail_id = 102,header_id = 11,EMPLOYEE_ID = 1000598,JOB_CODE = 77, work_date = '2016年2月9日',小時= 4.00
detail_id = 109,header_id = 12 ,employee_id = 1000598,job_code = 79, work_date ='2016-02-11',小時= 4。50
例如,這是在詳細表1000599 EMPLOYEE_ID數據:
detail_id = 121,header_id = 11,EMPLOYEE_ID = 1000599,JOB_CODE = 78, work_date ='2016- 02-10' ,小時= 8.00
detail_id = 122,header_id = 14,EMPLOYEE_ID = 1000599,JOB_CODE = 75, work_date = '2016年2月12日',小時= 3.00
例如因爲這是表1000600 EMPLOYEE_ID在詳細數據:
detail_id = 131,header_id = 11,EMPLOYEE_ID = 1000600,JOB_CODE = 72, work_date = '2016年2月11日',小時= 7.00
detail_id = 132,header_id = 13,EMPLOYEE_ID = 1000600,JOB_CODE = 75, work_date = '2016年2月17日',小時= 3.00
SQL查詢應返回1000598 EMPLOYEE_ID因爲1000598有數據f或者對於同一week_start_date ='2016-02-08',department_code = 33和department_code = 39。
SQL查詢應該返回1000599 employee_id,因爲對於同一week_start_date ='2016-02-08',1000599的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
並不多。
學校分配?你到目前爲止嘗試過什麼? –
大聲笑不是真的。這是工作。我嘗試過GROUP BY,但問題是我需要在employee_id上有所不同,以及放置位置和/或部門檢查邏輯的位置 – srh
請將您的嘗試與GROUP BY一起發佈,以便我們可以對其進行調試。 –