如果我有两张桌子
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_id
value
的平均值,或汇总公司value
/选择随机公司{ {1}}将所有平均值除以?
只是澄清一下。我不想要每家公司的表现。我希望每家公司的平均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
我很想知道为什么我被投票。
答案 0 :(得分:0)
如果你想要每个公司一行(正如你的评论似乎暗示的那样),那么你需要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
答案 1 :(得分:0)
试试这个:
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