mysql选择datetime查询来查找1岁,2岁等的ID

时间:2016-11-08 12:44:08

标签: mysql sql

我想要在过去1年或年份创建的ID> 1但是年< 2,依此类推。就像假设这是表格一样:

+----+--------------------------+---------------------+
| id | data                     | cur_timestamp       |
+----+--------------------------+---------------------+
|  1 | The time of creation is: | 2014-02-01 20:37:22 |
|  2 | The time of creation is: | 2015-01-01 20:37:22 |
|  3 | The time of creation is: | 2015-02-01 20:37:22 |
|  4 | The time of creation is: | 2015-12-01 20:37:22 |
|  5 | The time of creation is: | 2016-02-01 20:37:22 |
|  6 | The time of creation is: | 2016-04-01 20:37:22 |
+----+--------------------------+---------------------+

我想得到一张这样的表:

+-----------------------+-------+
| date range            | count |
+-----------------------+-------+
| last 1 year           | 3     |
| > 1 year & < 2 years  | 2     |
| > 2 years             | 1     |
+-----------------------+-------+

第一栏中的任何内容都可以。但我想按照上面的规定进行计数。我尝试过各种各样的事情。

select count(*) from ids where cur_timestamp >= date_sub(now(), interval 1 year);

这将给我一些过去一年的ID。同样,我可以扩展它以获得其他值。但是,有什么方法可以在一个查询中获取所有值吗?

3 个答案:

答案 0 :(得分:0)

这称为条件聚合。您必须添加更多条件才能获得所需的年数。

select 
count(case when cur_timestamp >= date_sub(now(), interval 1 year) then 1 end) last_1_yr,
count(case when cur_timestamp > date_sub(now(), interval 1 year) and cur_timestamp <= date_sub(now(), interval 2 year) then 1 end) bw_1_2_yrs,
count(case when cur_timestamp > date_sub(now(), interval 2 year) then 1 end) gt_2_yrs
from ids 

答案 1 :(得分:0)

这是代码:

 SELECT DATE(cur_timestamp) as date, COALESCE(count(*),0)  as count FROM ids  
WHERE DATE(cur_timestamp) >= DATE(NOW()) - INTERVAL 365 DAY GROUP BY DATE(cur_timestamp)

尝试这个我将从今天的365天的间隔中给出你的总计数。你可以改变你的日间隔。

答案 2 :(得分:0)

一种可行的方法(未经测试,请原谅任何拼写错误)是生成一系列时间范围并将其与您的ids表连接起来。

例如,这是为了给出过去100年中每年的所有计数: -

SELECT CONCAT('> ', interval_end, ' year & < ', interval_start, ' year'), COUNT(*)
FROM
(
    SELECT tns.acnt * 10 + units.acnt AS interval_end,  
            DATE_SUB(NOW(), INTERVAL tns.acnt * 10 + units.acnt YEAR) AS date_range_end,
            tns.acnt * 10 + units.acnt + 1 AS interval_start,
            DATE_SUB(NOW(), INTERVAL tns.acnt * 10 + units.acnt + 1 YEAR) AS date_range_start
    FROM
    (SELECT 1 AS acnt UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) units
    CROSS JOIN
    (SELECT 1 AS acnt UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 0) tens
) sub0
LEFT OUTER JOIN ids ON ids.cur_timestamp BETWEEN date_range_end AND date_range_start
GROUP BY CONCAT('> ', interval_end, ' year & < ', interval_start, ' year')