I have table with 3 columns: agent_id, log_id, date

|log_id |agent_id|date                 |
----------------------------------------
|0      |1037    |'2013-05-11 10:26:30'|
|1      |1041    |'2013-05-11 13:01:30'|
|0      |1029    |'2013-05-11 08:22:30'|
|0      |1058    |'2013-05-11 07:04:30'|
|0      |1087    |'2013-05-11 18:54:30'|
|1      |1039    |'2013-05-11 15:21:30'|
|0      |1056    |'2013-05-11 14:28:30'|
|0      |1039    |'2013-05-11 08:12:30'|

And now, I'd like to group this result:
When log_id = 1 then display date in column "logged in"
when log_id = 0 then display date in column "logged out"

I wrote sql query

select 
agent_id,
CASE WHEN log_id = 0 THEN date
ELSE NULL
END as "logged in",
CASE WHEN log_id = 1 THEN date
ELSE NULL
END as "logged out"
FROM agents
group by agent_id, log_id, date

But it is not working as expected.

|agent_id|logged_in           |logged_out          |
----------------------------------------------------
1041     |                    | 2013-05-11 13:01:30 
1029     |2013-05-11 08:22:30 |  
1039     |2013-05-11 08:12:30 |  
1058     |2013-05-11 07:04:30 |  
1039     |                    | 2013-05-11 15:21:30 
1056     |2013-05-11 14:28:30 |  
1087     |2013-05-11 18:54:30 |  
1037     |2013-05-11 10:26:30 |  

For example logged_in and logged_out where agent_id = 1039 should be in one row.

有帮助吗?

解决方案

Tkank you @fyr it works

select 
a.agent_id,
li.date,
lo.date
FROM agents a
LEFT JOIN agents li ON (li.agent_id=a.agent_id and li.log_id = 0)
LEFT JOIN agents lo ON (lo.agent_id=a.agent_id and lo.log_id = 1)
group by a.agent_id, li.date, lo.date

其他提示

You could use an aggregate function with your CASE. Also don't GROUP BY the log_id because the values are different, you have a 0 or 1 value which will cause different rows when grouping:

select agent_id,
  max(
      CASE 
        WHEN log_id = 0 THEN date
        ELSE NULL
      END) as "logged in",
  max(
      CASE 
        WHEN log_id = 1 THEN date
        ELSE NULL
      END) as "logged out"
FROM agents
group by agent_id;

See SQL Fiddle with Demo

Then depending on your database, you could further expand this query to GROUP BY date, meaning the date without the time included so you could get a login or logout value for each day. Here is a sample query using MySQL:

select agent_id,
  date_format(date, '%Y-%m-%d') date, 
  max(
      CASE 
        WHEN log_id = 0 THEN date
        ELSE NULL
      END) as "logged in",
  max(
      CASE 
        WHEN log_id = 1 THEN date
        ELSE NULL
      END) as "logged out"
FROM agents
group by agent_id, date_format(date, '%Y-%m-%d');

See Demo

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top