首先做一个总和然后乘以该值

时间:2016-08-04 09:14:12

标签: mysql sql sum

我今天在SQL中遇到一个问题,我似乎无法解决。任何帮助或指示将不胜感激。

我有以下2个表格 enter image description here

现在我想得到的是(labourentries.minutes_worked * price_per_hour / 60)AS价格,然后按每个实验类型对其进行分组并执行SUM(价格),以便获得每个labourtype的所有条目总数。< / p>

我在使用mySql,这里有一些示例数据 enter image description here

我到目前为止得到了一些sql,但无法完全解决我的问题。

SELECT SUM(labourentries.minutes_worked) AS minutes_worked,
       AVG(labourentries.price_per_hour) AS average_price,
       count(labourtypes.id) AS amount,
       labourtypes.labourtype
FROM labourtypes
INNER JOIN labourentries ON labourtypes.id = labourentries.labourtype_id
GROUP BY labourtypes.id  

在这里,我尝试对price_per_hour做一个平均值,然后对其进行分组,但差异太大而不可靠。

无论如何,请提前感谢您的帮助。 干杯!

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT SUM(PRICE) AS PRICE_PER_LABOURTYPE, A.LABOUR_TYPE  FROM
(SELECT (B.MINUTES_WORKED * B.PRICE_PER_HOUR / 60) AS PRICE, A.LABOUR_TYPE FROM LABOURTYPES A 
INNER JOIN LABORENTERIES B ON A.ID = B.LABOURTYPE_ID)
GROUP BY A.ID

答案 1 :(得分:0)

在用Dmitry Egorov的评论编辑查询后,我能够通过添加以下代码来解决问题:

sum(minutes_worked * price_per_hour / 60) as Price,

所以我的SQL查询变成了

SELECT SUM(labourentries.minutes_worked) AS minutes_worked,
sum(minutes_worked * price_per_hour / 60) as Price,
count(labourtypes.id) AS amount,
labourtypes.labourtype
FROM labourtypes
INNER JOIN labourentries ON labourtypes.id = labourentries.labourtype_id
GROUP BY labourtypes.id