由多个约会组成

时间:2017-05-02 20:49:29

标签: mysql group-by timestampdiff

我有这个表存储用户上次连接到服务器的时间:

function Mlim = get_diag_matrix_inf_limit(M)
  % get the diagonal
  M_diag = diag(M);

  % All possible cases
  I_nan = M_diag <= -1;
  I_0 = abs(M_diag) < 1;
  I_1 = M_diag == 1;
  I_inf = M_diag > 1;

  % Update diagonal
  M_diag(I_nan) = nan;
  M_diag(I_0) = 0;
  M_diag(I_1) = 1;
  M_diag(I_inf) = Inf;

  % Generate new diagonal matrix
  Mlim = diag(M_diag);
end

我可以选择并计算过去2个月内有效的ID:+----+----------------------------+-----------+ | id | last_connection | something | +----+----------------------------+-----------+ | 1 | 2017-03-23 10:39:14.000000 | bleh | | 2 | 2014-03-20 07:05:51.000000 | blah | | 3 | ... | ... | +----+----------------------------+-----------+ stats SELECT count(*) as '2months' FROM last_connection WHERE TIMESTAMPDIFF(DAY, SUBSTRING_INDEX(,或过去3个月{{1等等,这让我得到这样的东西:

, ' ', 1), CURDATE()) < 60

我的问题是:有没有办法在一个唯一的查询中对几个TIMESTAMPDIFF进行分组,并获得如下内容?

SELECT count(*) as '3months' ... < 90

2 个答案:

答案 0 :(得分:1)

SELECT sum(TIMESTAMPDIFF(DAY, SUBSTRING_INDEX(last_connection, ' ', 1), CURDATE()) < 30) as '1months',
       sum(TIMESTAMPDIFF(DAY, SUBSTRING_INDEX(last_connection, ' ', 1), CURDATE()) < 60) as '2months',
       sum(TIMESTAMPDIFF(DAY, SUBSTRING_INDEX(last_connection, ' ', 1), CURDATE()) < 90) as '3months' 
FROM stats

或更短

SELECT sum(last_connection > current_timestamp - interval 30 day) as '1months',
       sum(last_connection > current_timestamp - interval 60 day) as '2months',
       sum(last_connection > current_timestamp - interval 90 day) as '3months' 
FROM stats

答案 1 :(得分:0)

执行此操作的一种方法是使用UNION运算符,例如:

SELECT '1month', count(*)  
FROM stats
WHERE  TIMESTAMPDIFF(DAY, SUBSTRING_INDEX(last_connection, ' ', 1), CURDATE()) BETWEEN 0 AND 30

UNION

SELECT '2months', count(*)  
FROM stats
WHERE  TIMESTAMPDIFF(DAY, SUBSTRING_INDEX(last_connection, ' ', 1), CURDATE()) BETWEEN 31 AND 60

UNION

SELECT '3months', count(*)  
FROM stats
WHERE  TIMESTAMPDIFF(DAY, SUBSTRING_INDEX(last_connection, ' ', 1), CURDATE()) BETWEEN 61 AND 90

此外,您需要使用范围而不仅仅是<运算符来防止重复。