[英]SQL: How to add a column with the minimum value
I would appreciate your support, I'd like to build a SQL qry to obtain as result an additional comlumn with the minimum value of group of codes based on 2 tables. 多谢您的支持,我想构建一个SQL qry来获得一个额外的列,其结果是基于2个表的代码组的最小值。
For example:I have 2 tables 例如:我有2张桌子
Table: extract 表:提取物
AppCode | Phase |
------------------
AB | Phase 2
ABC | Phase 1
ABC | Phase 2
ABCD | Phase 1
ABCE | Phase 3
ABCE | Phase 2
Table: Phases 表:阶段
PhaseName | Objective
------------------
Phase 1 | 2
Phase 2 | 4
Phase 3 | 24
Output expected: 预期输出:
AppCode | PhaseName | Objective | MinObjetivo
------------------
AB | Phase 2 | 4 | 4
ABC | Phase 1 | 2 | 2
ABC | Phase 2 | 4 | 2
ABCD | Phase 1 | 2 | 2
ABCE | Phase 3 | 24 | 4
ABCE | Phase 2 | 4 | 4
Please Let me know; 请告诉我; if with this example is not enough
如果用这个例子还不够
This is basically a join
, but with a twist. 这基本上是一个
join
,但有所不同。 Most databases support window functions, and these will do what you want: 大多数数据库都支持窗口功能,而这些功能可以满足您的要求:
select e.appcode, p.phasename, p.objective,
min(p.objective) over (partition by e.appcode) as minObjetivo
from extract e join
phases p
on e.phase = p.phasename;
In MySQL: 在MySQL中:
SELECT e.appcode, p.phasename, p.objective, m.minobjectivo
FROM extract AS e
JOIN phases AS p ON e.phase = p.phasename
JOIN (SELECT e1.appcode, MIN(p1.objective) as minobjectivo
FROM extract AS e1
JOIN phases AS p1 ON e1.phase = p1.phasename
GROUP BY e1.appcode) AS m
ON e.appcode = m.appcode
This starts out as an ordinary join between extract
and phases
, to get the first 3 columns. 它以
extract
和phases
之间的普通联接开始,以获得前三列。 Then you write a subquery that gets the minimum objective for each appcode, and join this to get the additional column. 然后,编写一个子查询,该子查询获取每个应用程序代码的最低目标,并将其联接以获取其他列。
Here's another way to write it: 这是另一种写法:
SELECT e.appcode, p.phasename, p.objective, MIN(p1.objective) AS minobjectivo
FROM extract AS e
JOIN phases AS p ON e.phase = p.phasename
JOIN extract AS e1 ON e1.appcode = e.appcode
JOIN phases AS p1 ON e1.phase = p1.phasename
GROUP BY e.appcode, p.phasename
This is similar, but the additional joins are done in the main query instead of a subquery. 这是相似的,但是附加联接是在主查询而不是子查询中完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.