重复行上只有 select 最大分钟 DateDiff,SQL

Only select max minute DateDiff on duplicate rows, SQL

我有两个表,TableA 有列:Job、Machine、CutStart、CutEnd。 TableB 有 columns:job、开始、结束。 Table A 有作业和机器的主键。 TableB有job的主键。本质上,tableB 是来自 tableA 的多台机器的所有内容汇集在一起​​的地方。我需要拉出 tableA.CutStart 到 tableB.End 之间的最长时差。由于有多台机器与一个作业相关联,因此我在与每个作业相关的分钟数上有多个差异,我只需要 select 最大的一个。到目前为止,这是我的代码。另外,请注意作业是小日期时间的形式。还有一些其他各种 where 语句来删除坏数据。

SELECT tableA.Job, DateDiff(MINUTE, tableA.cutstart, tableB.end) as 'total minute'
From tableA
left join tableB on
tableA.Job = tableB.Job
where tableA.Job >= '2016-02-01' AND tableA.Job <= (DATEADD(Month, 1, '2016-02-01'))
AND datediff(Minute, tableA.cutstart, tableB.end) < 17280 AND datediff(Minute, tableA.cutstart, tableB.End) > 20
group by tableA.Job, tableA.CutStart, tableB.End order by tableA.Job

一个例子。 Table A 有作业 A 和 B,每台机器上有 3 台不同的机器,每台机器都有自己的切割起点和切割终点。 Table B 只有工作 A 和 B,每个工作只有一个开始和结束。如果你 运行 上面的代码你会得到 6 个结果,而我只想要 2 个。这 2 个结果是 tableA.cutstart 和 tableB.end 之间最大差距的时间差。

----------------更新------------

Table一个

Job   Machine            CutStart              CutEnd
A         5           2016-02-03 08:56      2016-02-03 10:50
A         6           2016-02-03 07:32      2016-02-03 9:42
A         7           2016-02-03 09:12      2016-02-03 11:15
B         5           2016-02-03 08:56      2016-02-03 10:50
B         6           2016-02-03 08:56      2016-02-03 10:50
B         7           2016-02-03 08:56      2016-02-03 10:50

TableB

Job      Start                 End
A      2016-02-03 13:53       2016-02-03 15:32
B      2016-02-03 13:53       2016-02-03 15:32

当前结果

Job      "Minute difference"
A              54
A             112
A               96
B             154
B             93
B             217

想要的结果

Job      "Minute difference"
A             112
B             217

我只想select每项工作中最长的小步舞曲差异。此外,数字不相加,它们只是占位符。

------------------------最终解决方案--------------------

SELECT tableB.Job, DateDiff(MINUTE, (
  SELECT MIN(tableA.cutstart) 
  FROM tableA
  WHERE tableA.Job=tableB.Job
), tableB.end) as [total minute]
From tableB
where {whatever conditions you want}

如何像 SQL 开发人员一样思考:

"I need to pull the LONGEST..."

转换为:

"I need the top 1, ordered by..."

所以像这样:

SELECT TOP 1 tableA.Job, DateDiff(MINUTE, tableA.cutstart, tableB.end) as [total minute]
From tableA
left join tableB on
tableA.Job = tableB.Job
where {whatever conditions you want)
ORDER BY DateDiff(MINUTE, tableA.cutstart, tableB.end) DESC

编辑:如果你希望每个工作的时间最长运行,答案更容易思考。

该作业只有一个结束时间,因此每个作业的最长 运行 将是表 A 中具有最早开始时间的连接行。

这里有一种方法(有很多):

SELECT tableB.Job, DateDiff(MINUTE, (
  SELECT MIN(tableA.cutstart) 
  FROM tableA
  WHERE tableA.Job=tableB.Job
), tableB.end) as [total minute]
From tableB
where {whatever conditions you want}

请注意将与 TableB 相关的条件放在主 WHERE 子句中,并将与 TableA 相关的条件放在子查询中。