我在弄清楚以下 mysql 查询时遇到了一些麻烦。
这是一种时间跟踪,用户根据他们所做的任务有一定的费率。而且我需要有一个摘要,以便我知道在周末向用户支付什么费用。
-----------tSessions---------------------------
|id |userid |typeid |session_length_min
-----------------------------------------------
|1 |1 |1 |30
-----------------------------------------------
|2 |1 |1 |45
-----------------------------------------------
|3 |1 |2 |(null)
-----------------------------------------------
|4 |2 |2 |(null)
-----------------------------------------------
-----------tUsers-----------------------------------------------------------------------------------
|id |name |rate_cleaning_30_min |rate_cleaning_45_min |rate_kitchenwork |rate_dogwalking
----------------------------------------------------------------------------------------------------
|1 |Tom |30 |50 |40 |20
----------------------------------------------------------------------------------------------------
|2 |Joe |35 |60 |45 |20
----------------------------------------------------------------------------------------------------
|3 |Dave |40 |60 |30 |10
----------------------------------------------------------------------------------------------------
-----------tTypes----------------
|id |name
---------------------------------
|1 |Cleaning
---------------------------------
|2 |Kitchenwork
---------------------------------
|3 |Dogwalking
---------------------------------
============== Required Result ====================
|username |sessioncount |amount_to_pay
---------------------------------------------------
|Tom |2 |120
---------------------------------------------------
|Joe |1 |45
---------------------------------------------------
如果我的方法不太成功,则下面的查询是一个:
SELECT
tSessions.id,
tSessions.userid,
tSessions.typeid,
tSessions.session_length_min,
SUM(tUsers.rate_cleaning_30_min) AS rate_cleaning_30_min_sum,
SUM(tUsers.rate_cleaning_45_min) AS rate_cleaning_45_min_sum,
SUM(tUsers.rate_kitchenwork) AS rate_kitchenwork,
SUM(tUsers.rate_dogwalking) AS rate_dogwalking,
Count(*) AS sessioncount,
FROM
tSessions
INNER JOIN tUsers ON tSessions.userid = tUsers.id
WHERE WEEKOFYEAR(FROM_UNIXTIME(datetime))=WEEKOFYEAR(NOW())-1
GROUP BY
tSessions.userid,
tSessions.typeid