2016-08-04 71 views
0

我今天遇到了一個SQL問題,我似乎無法解決。任何幫助或指針,將不勝感激。首先做一個總和然後乘以值

我有以下2個表 enter image description here

現在我想要得到的是(labourentries.minutes_worked * price_per_hour/60)AS價格,然後以這組由每labourtype,做一個SUM(價格),所以我會得到每個實驗類型的所有條目總數。

我使用的是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的平均值,然後組,但差別太大是可靠的。

無論如何感謝提前的幫助。 乾杯!

+1

需要說明... 請寫2或3行labourtypes表 請寫出2排或3排表格 ---然後 請寫出2或3行您最終希望看到的結果 –

+0

也標記使用的dbms產品。 – jarlh

+1

您是否需要通過'labourtypes.id'的'labourentries' _and_ totals中的'price''或僅僅總計?如果後者是這種情況(並且你的代碼建議如此),那麼你可以簡單地使用'sum(minutes_worked * price_per_hour/60)作爲Price'。看到簡化的演示:http://sqlfiddle.com/#!9/ce93a/2 –

回答

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 
0

與梅德葉戈羅夫的評論編輯查詢我能加入這行代碼來解決此問題後:

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 
相關問題