在两个字段相同的情况下,如何求和和和平均值?

r7xajy2e  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(399)

脚本:

SELECT
m.order,
d.product,
d.nto,
p.code,
p.weight,
p.country
FROM so_order_master m
JOIN so_order_detail d ON d.order_id = m.id
JOIN product p ON p.product = s.product

当前结果:

ORDER    PRODUCT         NTO        CODE         WEIGHT  COUNTRY
5014221  Z81-2R2R-1R     32,7303    3913 38 98   2,05    US
5014222  XX-811-RR4      26,2851    1718 19 81   4       US
5014222  12X-8-R7R81     2,4969     8489 91 88   0,035   TW
5014222  XX-4X8-RR1      19,0404    1718 19 81   1,2     SE
5014222  XX-84Y          18,8436    1718 19 81   1,5     US
5014222  YR7-Y147        61,1064    8489 91 88   0,4     TW
5014222  XX-8R8-RR4      63,9846    1718 19 81   4       US
5014222  XX-8R4-RR4      26,2851    1718 19 81   3       US

我需要一个脚本来帮助我:
求和 NTO 具有相同代码和国家/地区的字段;
平均 weight 具有相同代码和国家/地区的字段;
订单和产品可能来自第一行(不是必需的)。
预期结果:

ORDER     PRODUCT       NTO_SUM     CODE        WEIGHT_AVG  COUNTRY
5014222   XX-4X8-RR1    19,0404     1718 19 81  1,2         SE
5014222   XX-811-RR4    135,3984    1718 19 81  3,125       US
5014221   Z81-2R2R-1R   32,7303     3913 38 98  2,05        US
5014222   12X-8-R7R81   63,6033     8489 91 88  0,2175      TW

提前感谢您的帮助!

gblwokeq

gblwokeq1#

正如你提到的,你应该按“代码和国家”进行汇总。您的查询应该是:

select
  max(m.order) as ordr,
  max(d.product) as product,
  sum(d.nto) as nto,
  p.code,
  avg(p.weight) as weight,
  p.country
from so_order_master m
join so_order_detail d on d.order_id = m.id
join product p on p.product = s.product
group by p.code, p.country
de90aj5v

de90aj5v2#

你必须和 GROUP BY 说明。请参见:

select MAX(m.order), MAX(d.product), SUM(d.nto) AS nto_sum, p.code, AVG(p.weight) AS weight_avg, p.country
from so_order_master m
join so_order_detail d on d.order_id = m.id
join product p on p.product = s.product
GROUP BY p.code, p.country

根据数据库提供程序的不同,在 AVG() 或者 AVERAGE() 姓名。

相关问题