联合表的总和

时间:2013-05-19 06:08:07

标签: mysql

这可能已经在某个地方得到了解答,但我找不到它。 如果有人可以再次帮助我使用这个sql语句,那将不胜感激。

这是我到目前为止的sql语句:

SELECT * , Round( (Rate * TIME_TO_SEC( Total ) /3600 ) , 2) AS revenue
FROM (SELECT event.eventID, event.staffID, event.role, TIMEDIFF( Time, Pause ) 
AS Total,
CASE WHEN Position = 'Teamleader'
THEN (Teamleader)
WHEN Position = 'Waiter'
THEN (Waiter)
ELSE '0'
END AS Rate
FROM event, rates, eventoverview
WHERE Storno =0
AND event.eventID= eventoverview.eventID
AND event.clientid = rates.clientid
GROUP BY event.eventID, event.clientID)q1
GROUP BY q1.staffID

我得到的表现在给我一个每个员工和事件的总费率。 但我想要达到的是每个员工的费率之和。 所以基本上是收入的总和。

希望有人可以帮助我。提前致谢

1 个答案:

答案 0 :(得分:0)

您可以将查询括在子查询中,并在外部查询中执行此操作,如下所示:

SELECT *,
  SUM(revenue)
FROM
(

    SELECT * , 
      Round( (Rate * TIME_TO_SEC( Total ) /3600 ) , 2) AS revenue
    FROM 
    (
       SELECT 
         event.eventID, 
         event.staffID, 
         event.role, 
         TIMEDIFF( Time, Pause ) AS Total,
         CASE WHEN Position = 'Teamleader' THEN (Teamleader)
              WHEN Position = 'Waiter'     THEN (Waiter)
              ELSE '0'
         END AS Rate
       FROM event
       INNER JOIN rates         ON event.clientid = rates.clientid
       INNER JOIN eventoverview ON event.eventID  = eventoverview.eventID
       WHERE Storno =0
       GROUP BY event.eventID, event.clientID
    )q1
    GROUP BY q1.staffID
) AS t
GROUP BY staffID;

请注意:由于SELECT *仅使用GROUP BY staffIDGROUP BY不在{{1}},因此您可能会收到不一致的数据{1}}子句需要用聚合函数括起来,否则mysql会得到一个任意值。不建议这样做,这不是标准方法。