Guns
Guns

Reputation: 2728

Getting Report with one MySQL query

I have a MySQL Table 'logs' with the below data

id  username    status   statusdatetime   mailid
-----------------------------------------------------------------------
1   abc         pull     3/21/2013 10:04  1753
2   abc         step1    3/21/2013 10:13  1753
3   abc         step2    3/21/2013 10:17  1753
4   abc         step1    3/21/2013 10:46  1753
5   abc         step2    3/21/2013 10:54  1753
6   abc         step3    3/21/2013 11:09  1753
7   abc         mailsent 3/21/2013 11:10  1753
8   abc         pull     3/21/2013 11:11  2113
9   abc         step1    3/21/2013 11:18  2113
10  abc         step1    3/21/2013 11:32  2113
11  abc         step2    3/21/2013 11:33  2113
12  abc         step3    3/21/2013 11:44  2113
13  abc         mailsent 3/21/2013 11:44  2113
14  def         pull     3/21/2013 10:21  120
15  def         step1    3/21/2013 10:22  120
16  def         step2    3/21/2013 10:36  120
17  def         step1    3/21/2013 10:37  120
18  def         step2    3/21/2013 10:38  120
19  def         step3    3/21/2013 10:39  120
20  def         mailsent 3/21/2013 10:39  120
21  def         pull     3/21/2013 10:40  1203
22  def         step1    3/21/2013 10:41  1203
23  def         step2    3/21/2013 10:50  1203
24  def         step3    3/21/2013 10:54  1203
25  def         mailsent 3/21/2013 10:55  1203

The help that i request is the below output:

id  username    mailid  Time (Seconds)
-----------------------------------------------------------------------
1   abc         1753    3977
2   abc         2113    1991
3   def         120     1101
4   def         1203    888

Explanation:

Each user and each mailid are grouped and the time difference between 'mailsent' and 'pull' from the column 'status' to be calculated!

is this possible in one select query?

Upvotes: 2

Views: 120

Answers (2)

Suhel Meman
Suhel Meman

Reputation: 3852

If u have same sequence which goes from pull to mailsent status for each mailid, then use below query

 select
     username,
     mailid,
     TIMESTAMPDIFF(SECOND,min(statusdatetime),max(statusdatetime)) as `Time`
 from logs
 group by mailid;

Upvotes: 1

Meherzad
Meherzad

Reputation: 8553

Try this query

SELECT  
   a.username,
   a.mailid, 
   TIME_TO_SEC(TIMEDIFF(b.statusdatetime, a.statusdatetime)) AS DIFF
FROM 
   tbl a 
INNER JOIN
   tbl b 
ON 
   a.mailid = b.mailid AND 
   a.status = 'pull' AND
   b.status = 'mailsent'
GROUP BY 
   username, 
   mailid

FIDDLE

Upvotes: 1

Related Questions