加入一对多,得到平均数除以一?

mefy6pfw  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(292)

如果我有两张table

companies
id
value

companies_products
company_id
order_count

我的问题如下:

SELECT
  (AVG(companies_products.order_count) / companies.value) as special_number
FROM companies
JOIN on companies_products on companies_products.company_id = companies.id

这能正确地划分 companies_products.order_count 就这样 company_idvalue 或者是把这些公司合并起来 value /随机挑选公司 value 把所有的平均数除以?
只是澄清一下。我不想要每个公司的业绩。我要每个公司平均值的总平均值 order_count /那些公司 value 作为一个大平均数。
我的问题不是这个查询没有运行,我只是担心它没有实现我所要寻找的,并且没有创建一些新表,我不知道如何证明它是否有效。我有个号码我只是不确定是不是这个号码

Sample Data:

companies data:

id: 1
value: 10

id: 2
value: 20

companies_products
company_id: 1
order_count: 20

company_id: 1
order_count: 40

company_id: 2
order_count: 20

company_id: 2
order_count: 20

输出

Result:
special_number: 2

Explanation:
avg of first company would be 3
avg of second company would be 1

我很想知道为什么我被否决了。

pzfprimi

pzfprimi1#

如果你希望每家公司一行(正如你的评论似乎暗示的那样),那么你需要 group by :

select c.id, avg(cp.order_count) / c.value) as special_number
from companies c join
     companies_products cp
     on cp.company_id = c.id
group by c.id, c.value;  -- the "c.value" is technically redundant, but I think it adds clarity
hgb9j2n6

hgb9j2n62#

试试这个:

select (SELECT AVG(companies_products.order_count)  FROM companies
JOIN on companies_products on companies_products.company_id = companies.id)/ cast(companies.value as float)
FROM companies
JOIN on companies_products on companies_products.company_id = companies.id

相关问题