-1

我有 3 列的表:agent_id、log_id、日期

|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'|

现在,我想对这个结果进行分组:然后在“登录”列中
显示日期 ,然后在“注销”列中显示日期log_id = 1
log_id = 0

我写了sql查询

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

但它没有按预期工作。

|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 |  

例如,agent_id = 1039 的logged_in 和logged_out 应该在一行中。

4

2 回答 2

1

Tkank 你@fyr 它有效

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
于 2013-05-13T11:03:03.580 回答
1

您可以将聚合函数与CASE. 也不要GROUP BY因为log_id值不同,所以你有一个0or1值,它会在分组时导致不同的行:

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;

请参阅带有演示的 SQL Fiddle

然后根据您的数据库,您可以进一步将此查询扩展到GROUP BY日期,这意味着不包括时间的日期,因此您可以获得每天的登录或注销值。这是使用 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');

演示

于 2013-05-13T11:04:31.723 回答