[英]Calculate an average with 2 rows of 2 different tables
I'm quite new to MySQL and currently I'm struggling with a problem.我对 MySQL 很陌生,目前我正在努力解决一个问题。
I have 2 Tables (techlog and sales).我有 2 个表(技术日志和销售)。 What I intend to do now is, get a sum out of a column in techlog and the same with sales.我现在打算做的是,从 techlog 中的列中获取总和,与 sales 相同。 These two sums I'd need to calculate something new Sum(sales.row) / Sum(techlog.row).这两个总和需要计算新的 Sum(sales.row)/Sum(techlog.row)。 The idea for this is that I could get a Price per Minute.这样做的想法是我可以获得每分钟的价格。 Is something like that possibe?有这样的可能吗?
Both tables share column with the same ID.两个表共享具有相同 ID 的列。 Further some Columns such as the Immatriculation is also available on both tables.此外,两张表上还提供了一些列,例如 Immatriculation。
What I've tried so far:到目前为止我已经尝试过:
use dbm_project;
SELECT techlog.Immatriculation, sum(techlog.TimeTOT), sum(sales.total)
FROM techlog
INNER JOIN sales
ON techlog.Immatriculation = sales.Immatriculation
GROUP BY techlog.Immatriculation
My apologies in advance since I find it hard to formulate my problem with missing experience.我提前道歉,因为我发现很难用缺少的经验来阐述我的问题。
Long story short: I want to calculate two values of two different tables and with those I want to calculate something new.长话短说:我想计算两个不同表的两个值,并用那些我想计算一些新的值。
This is a job for subqueries.这是子查询的工作。
One is一个是
SELECT Immatriculation, sum(TimeTOT) TimeTot
FROM techlog
GROUP BY Immatriculation
The other is另一个是
SELECT Immatriculation, sum(total) SalesTot
FROM sales
GROUP BY Immatriculation
Then you join them together然后你把他们联合起来
SELECT t.Immatriculation, t.TimeTot, s.SalesTot
FROM (
SELECT Immatriculation, sum(TimeTOT) TimeTot
FROM techlog
GROUP BY Immatriculation
) t
LEFT JOIN (
SELECT Immatriculation, sum(total) SalesTot
FROM sales
GROUP BY Immatriculation
) s ON t.Immatriculation = s.Immatriculation;
This works because....这有效,因为....
Immatriculation
value.两个子查询中的每一个都具有每个Immatriculation
值的一行。 So you get one row in your result set for each.因此,每个结果集中都有一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.