简体   繁体   English

带JOIN和按平均分组的SQL

[英]SQL with JOIN and Group By Plus Average

I am looking to generate results of my shop efficiencies. 我希望产生提高车间效率的结果。 To do this I will need data from 3 different tables JOMAST, JODRTG and INRTGS. 为此,我需要来自3个不同表JOMAST,JODRTG和INRTGS的数据。 So I have come up with the following Query: 所以我想出了以下查询:

select jomast.fpartno AS 'Part Number',
JODRTG.foperno AS 'OP Number',
JODRTG.fopermemo As ' Description',
JODRTG.fpro_id AS 'Work Center',
jodrtg.fprod_tim AS ' Act. Production Time',
inrtgs.fuprodtime AS 'Est. Prodution Time'
from jodrtg
Left join jomast on jodrtg.fjobno = jomast.fjobno
left join inrtgs on jomast.fpartno = inrtgs.fpartno

Now what I need to do is average out the Act. 现在,我需要做的就是使法案平均化。 Production Time. 生产时间。 And get things down to the Part Number with all of the OP numbers for that part. 然后将有关该零件的所有OP编号简化为零件编号。

When I try and Group By JOMAST.fpartno I get an error that it cannot use and outer column. 当我尝试对Group By JOMAST.fpartno ,出现错误,指出它无法使用并且位于外部列。 If I do Group By on the Operation number, then all Operation 10's for every part will be combined. 如果我在工序编号上进行分组依据,则每个零件的所有工序10将被合并。 Which, is not the desired result. 这不是期望的结果。

Can someone please point me in the direction I need to go to achieve my result? 有人可以指出我要达到目标的方向吗?

It sounds like you want to have multiple rows all showing the same jodrtg.fpartno , all showing different jodrtg.fprod_tim , but all showing the average (same) value of jodrtg.fprod_tim yes? 这听起来像你希望拥有多个行的所有显示相同jodrtg.fpartno ,无不呈现出不同的jodrtg.fprod_tim ,但所有显示的平均值(下同)值jodrtg.fprod_tim是吗?

If so, add: 如果是这样,请添加:

AVG(jodrtg.fprod_tim) OVER(PARTITION BY jodrtg.fpartno) as avg_for_all_fprod_tim

as a column in your list of columns you're selecting. 作为您选择的列列表中的一列。

For more info you can google PARTITION BY, but think of it like an instruction to perform a GROUP BY x, AVG(y) (or sum, max, whatever) on the data, but then put that AVG into the row data for each row where x is present.. 有关更多信息,您可以在Google PARTITION BY上进行搜索,但可以将其视为对数据执行GROUP BY x,AVG(y)(或总和,最大值等)的指令,然后将每个AVG放入行数据中x所在的行。

Essentially it's the same as writing a smaller subquery of (SELECT jodrtg.fpartno, avg(jodrtg.fprod_tim) as avg_for_all_frod_tim FROM blah GROUP BY jodrtg.fpartno) and then joining it back to your main query 从本质上讲,这与编写较小的子查询(SELECT jodrtg.fpartno, avg(jodrtg.fprod_tim) as avg_for_all_frod_tim FROM blah GROUP BY jodrtg.fpartno)然后将其重新连接到主查询相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM