对同一查询中的SQL查询结果求和

时间:2019-01-15 13:59:47

标签: mysql sql mysqli phpmyadmin

我试图将第三列中两列的结果求和

SELECT A.Date, A.EmpID,
SUM(CASE WHEN State = 'active' THEN A.MinutesatState ELSE 0 END) AS active, 
SUM(CASE WHEN State = 'idle' THEN A.MinutesatState ELSE 0 END) AS idle,

FROM time A join ttld.login B on A.EmpID=B.username 
WHERE DATE = '01-15-2019' GROUP BY A.EmpID

第三列应该是我在查询中尝试过的活动和空闲数字的总和,但是由于我很少甚至根本不知道我无法运行它

SELECT A.Date, A.EmpID,
SUM(CASE WHEN State = 'active' THEN A.MinutesatState ELSE 0 END) AS active, 
SUM(CASE WHEN State = 'idle' THEN A.MinutesatState ELSE 0 END) AS idle,

SUM(CASE WHEN State = ('idle','active') THEN A.MinutesatState ELSE 0 END) AS Total_of_active_and_Idle

FROM time A join ttld.login B on A.EmpID=B.username 
WHERE DATE = '01-15-2019' GROUP BY A.EmpID

2 个答案:

答案 0 :(得分:0)

您可以在下面尝试-您需要添加(“空闲”,“活动”)

calc(100% + 15px)

答案 1 :(得分:0)

您需要IN子句或= any (),但是MySQL的缩写是case . . end

SELECT A.Date, A.EmpID,
       SUM( State = 'active' ) AS active, 
       SUM( State = 'idle' ) AS idle,
       SUM( State = any('idle','active') ) AS Total_of_active_and_Idle
FROM time A JOIN
     ttld.login B 
     ON A.EmpID = B.username 
WHERE DATE = '01-15-2019' 
GROUP BY A.EmpID;