SQL group by在两列中的日期时不起作用

时间:2013-05-13 10:50:57

标签: sql group-by case-when

我有3列的表: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'|

现在,我想将这个结果分组:
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 |  

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以使用CASE的聚合函数。另请注意,不要GROUP BY log_id,因为值不同,您有01值,这会在分组时产生不同的行:

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

然后,根据您的数据库,您可以进一步将此查询扩展到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');

请参阅Demo