首先让我道歉,如果这没有任何意义。我花了一些时间把它写下来并自己理解。如果有什么令人困惑,我道歉。我是新手,并尽力解释。我也为qustion标题道歉,如果它不代表。如果有人知道更好的标题,请编辑或进行必要的更改。
我有两个表JOBS和PHASES。
JOBS
Id
Job_Type (ex. 0 = import)
Title
PHASES
Id
Jobs_Id
Phase_Type
Title
Start_Time
End_Time
Duration
每个作业/作业类型可以有任意数量的阶段 - 每个阶段都有一个开始,结束和持续时间
我想从PHASES表中选择字段jobs_id,start_time,end_time和duration 并为每个job_type添加所有持续时间(例如:job_type = 0这是一个导入作业)
SELECT jobs_id, start_time, end_time, duration FROM phases
JOIN jobs ON phase.jobs_id = jobs.id
WHERE jobs.job_type=0
返回jobs_id 将earlist开始时间作为开始返回 将最新的结束时间作为结束返回 返回它们的总持续时间所有TotalDuration
示例,如果以下数据在JOBS表中(Id,Job_Type,Title)
1, 0, Import
以下数据位于PHASES表中(id,job_id,phase_type,title,start,end,duration)
1, 1, 1, 0, Run Preprocessor, 10/18/2012 8:52 PM, 10/18/2012 9:00 PM, 00:08:00
2, 1, 2, 1, Massage Data, 10/18/2012 9:00 PM, 10/18/2012 9:05 PM, 00:05:00
3, 1, 3, 2, Run Postprocessor, 10/18/2012 9:05 PM, 10/18/2012 9:07 PM, 00:02:00
4, 2, 1, 0, Run Preprocessor, 10/18/2012 9:15 PM, 10/18/2012 9:20 PM, 00:05:00
5, 2, 2, 1, Massage Data, 10/18/2012 9:20 PM, 10/18/2012 9:25 PM, 00:05:00
6, 2, 3, 2, Run Postprocessor, 10/18/2012 9:30 PM, 10/18/2012 9:35 PM, 00:05:00
上面显示了两个作业(job_type = 0)的信息(阶段)
我需要一个SQL语句,它可以组合各个阶段并显示earlist开始和最新结束,以及总持续时间。我希望返回此信息(Job_id,Start,End,TotalDuration)
1, 10/18/2012 8:52 PM, 10/18/2012 9:07 PM, 00:05:00
2, 10/18/2012 9:15 PM, 10/18/2012 9:35 PM, 00:15:00
答案 0 :(得分:1)
假设您的总持续时间不会超过1天,这将有效。如果超过一天,则需要在持续时间列中的HH:MM:SS
之前添加一个表达式。
select job_id,
min(start_time) start_time,
max(end_time) end_time,
CONVERT(CHAR(8), max(end_time)-min(start_time), 8) totalduration
from phases
group by job_id
-- sample data --
create table phases (job_id int, start_time datetime, end_time datetime);
insert phases values (1, '20121019 12:45', '20121019 13:15');
insert phases values (1, '20121019 13:15', '20121019 13:45');
insert phases values (1, '20121019 14:00', '20121019 15:12');
-- result --
job_id start_time end_time totalduration
1 2012-10-19 12:45:00.000 2012-10-19 15:12:00.000 02:27:00
答案 1 :(得分:0)
DECLARE @jobs TABLE(
jobid BIGINT NOT NULL
)
INSERT INTO @jobs (jobid)
VALUES (1)
, (2)
, (3)
DECLARE @phases TABLE(
phaseId BIGINT NOT NULL,
jobId BIGINT NOT NULL,
startTime datetime not null,
endTime datetime not null
)
INSERT INTO @phases (phaseId, jobId, startTime, endTime)
VALUES (1,1, '10/18/2012 8:52 PM', ' 10/18/2012 9:00 PM')
, (2, 1, '10/18/2012 9:00 PM', '10/18/2012 9:05 PM')
, (3, 1, '10/18/2012 9:05 PM', '10/18/2012 9:07 PM')
, (4, 2, '10/18/2012 9:15 PM', '10/18/2012 9:20 PM')
, (5, 2, '10/18/2012 9:20 PM', '10/18/2012 9:25 PM')
, (6, 2, '10/18/2012 9:30 PM', '10/18/2012 9:35 PM')
SELECT j.jobid, MIN(p.startTime) as startTime
, MAX(p.endTime) as endTime
, CONVERT(TIME(0),MAX(p.endTime)-MIN(p.startTime)) as duration
FROM @phases p
JOIN @jobs j ON j.jobid = p.jobId
GROUP BY j.jobid