2013-07-25 16 views
1

我試圖讓下面的select語句正常工作。我試圖爲每個代理獲得一行&包含min(time)其中agent-state ='登錄'的日期,其中agent-state ='註銷'的最大時間(time),timediff(max(時間) ,min(time))和總和(持續時間),其中agent-state ='Ready'MYSQL:在單個語句中選擇多個if(field ='x'max(time)/ if(field ='y'min(time))的值

我當前的SQL語句並不完整,因爲我剛剛獲得正確的最小/最大時間值並打中因爲它現在坐着,所以返回登錄最小時間,但不是登出最大時間。

AGENT, DATE,   TIME,  DURATION, AGENT_STATE 
Alex, 2013-01-01, 07:25:37, 00:00:00, Logged-in 
Alex, 2013-01-01, 07:26:01, 00:24:48, Ready 
Alex, 2013-01-01, 07:54:20, 00:21:47, Ready 
Alex, 2013-01-01, 08:28:11, 00:03:00, Ready 
Alex, 2013-01-01, 08:34:11, 00:06:29, Ready 
Alex, 2013-01-01, 08:44:30, 00:05:14, Ready 
Alex, 2013-01-01, 08:53:29, 00:06:52, Ready 
Alex, 2013-01-01, 09:03:48, 00:12:13, Ready 
Alex, 2013-01-01, 09:31:56, 00:36:44, Ready 
Alex, 2013-01-01, 09:32:27, 14:58:51, Logout 
Alex, 2013-01-01, 10:11:37, 00:00:00, Logged-in 
Alex, 2013-01-01, 10:12:26, 00:54:44, Ready 
Alex, 2013-01-01, 11:09:28, 00:47:48, Ready 
Alex, 2013-01-01, 11:57:33, 00:16:54, Ready 
Alex, 2013-01-01, 12:15:15, 00:17:32, Ready 
Alex, 2013-01-01, 12:34:44, 00:13:32, Ready 
Alex, 2013-01-01, 12:51:04, 00:16:44, Ready 
Alex, 2013-01-01, 13:12:36, 00:31:38, Ready 
Alex, 2013-01-01, 13:49:46, 00:39:14, Ready 
Alex, 2013-01-01, 14:31:42, 00:28:45, Ready 
Alex, 2013-01-01, 15:00:27, 14:58:51, Logout 

SQL語句:

select 
`agent`, 
`date`, 
if(`agent_state` = 'Logged-in', min(`time`), null) as `min_login`, 
if(`agent_state` = 'Logout', max(`time`),null) as `max_logout` 
from 
t_cisco_agent_state_details 
group by 
`agent`, `date` 
order by 
`agent`, `date`, `time` asc; 

感謝任何幫助或建議。

Jim

+0

如何知道最大時間不返回?你能顯示你的查詢結果嗎?是否因爲某些時候代理只是登錄而沒有註銷? –

回答

2

你不能這樣做。您爲「其他」列獲得空值的原因是因爲按代理和日期分組時,該agent_state不存在。如果您將agent_state添加到組中 - 您將獲得每個代理/日期3行。這不是你想要的。

您需要一個子查詢或一對自連接。嘗試如下所示:

SELECT agent, 
     date, 
     MIN(dur)      AS total_duration, 
     TIMEDIFF(MIN(maxt), MIN(mint)) AS time_difference_between_login_and_out, 
     MIN(maxt)      AS logout_time, 
     MIN(mint)      AS login_time 
FROM (SELECT agent, 
       date, 
       IF(agent_state = 'Ready', SUM(time), NULL)  AS dur, 
       IF(agent_state = 'Logged-in', MIN(time), NULL) AS mint, 
       IF(agent_state = 'Logout', MAX(time), NULL) AS maxt, 
       agent_state 
     FROM t_cisco_agent_state_details 
     GROUP BY agent, 
        date, 
        agent_state) AS subq 
GROUP BY agent, 
      date 

子查詢爲每個代理程序狀態,代理程序和日期創建一行。然後,您可以利用外部查詢將您的時間拉出來,該查詢按代理和日期進行分組。

+0

謝謝!這正是我沒有想到的......幾年來,實際上並沒有在SQL中。再次感謝! – jconnors