获取行数+插入的最后一行

时间:2018-08-01 09:53:03

标签: mysql sql

我有这个sql:

SELECT count(*) as nb, data_type, rawValue, createdAt 
FROM my_table WHERE data_type in('t','r', 'b') 
AND  CreatedAt >= DATE_SUB(NOW(), interval 24 HOUR) 
AND CreatedAt <= NOW() AND device=27 AND id=462 
group by data_type order by createdAt DESC ;

现在我得到这样的数据:

nb       data_type       rawValue           createdAt
20       t               test               2018-08-01 07:30:30
20       r               test               2018-08-01 08:30:30

对于data_type = t,我有2018-08-01 10:10:23的行,但是由createdAt获取第一个值,而不是最后一个。你能帮我吗 ?提前谢谢。

1 个答案:

答案 0 :(得分:0)

看来db是mysql, 当您将使用聚合函数时,选择列应位于group by子句中。我们知道now()返回的是当前的当前日期时间,如您给定的间隔24小时,所以仅注意选择记录时记录是否在此持续时间内,因为除group by子句列外,您的查询几乎可以,我将这些列放在组中按条款

您希望每个data_type有1行,所以我会像下面这样更改

    select T.nd,T.data_type,A.rawValue,T.createdAt from
   (
    SELECT count(*) as nb, data_type, 
    max(createdAt) as createdAt
    FROM table WHERE data_type in('t','r', 'b') 
    AND  CreatedAt >= DATE_SUB(NOW(), interval 24 HOUR) 
    AND CreatedAt <= NOW() AND device=27 AND id=462 
    group by data_type 
    ) as T left join table A
   on T.createdAt=A.createdAt
  and T.data_type=A.data_type
    where A.data_type in ('t','r', 'b')
   AND  A.CreatedAt >= DATE_SUB(NOW(), interval 24 HOUR) 
    AND A.CreatedAt <= NOW() AND device=27 AND id=462 

如果您共享表的样本数据和预期的输出,那就太好了