为什么此GROUP BY Mysql查询不起作用?

时间:2018-11-27 06:49:27

标签: mysql

SELECT time.EmpID, time.Date,
SUM(MinutesatState) AS active FROM time WHERE State = 'active'
GROUP BY time.EmpID, time.Date;

以上查询有效

SELECT time.EmpID, time.Date,
SUM(MinutesatState) AS idle FROM time WHERE State = 'idle'
GROUP BY time.EmpID, time.Date;

上面的查询也可以

但是当我在同一条语句中运行两个查询时,它不起作用

SELECT time.EmpID, time.Date,
SUM(MinutesatState) AS active FROM time WHERE State = 'active'
SUM(MinutesatState) AS idle FROM time WHERE State = 'idle'
GROUP BY time.EmpID, time.Date;

2 个答案:

答案 0 :(得分:1)

您的上一个查询在语法上是错误的。您不能像这样使用FROM子句。您正在寻找使用CASE..WHEN子句进行条件聚合。

SELECT 
  EmpID, 
  Date,
  SUM(CASE WHEN State = 'active' THEN MinutesatState ELSE 0 END) AS active, 
  SUM(CASE WHEN State = 'idle' THEN MinutesatState ELSE 0 END) AS idle
FROM time
GROUP BY EmpID, Date;

答案 1 :(得分:0)

您可以在分组依据列中包含状态。

SELECT time.EmpID, time.Date,State,
SUM(MinutesatState) As SumOfMinutes FROM time GROUP BY time.EmpID, time.Date,State;