2016-11-08 20 views
0

我想要在过去1年或年份> 1年但创建年份为< 2的ID,等等。像想,如果是这样的表:mysql select datetime查询找到1岁,2岁等的ID

+----+--------------------------+---------------------+ 
| 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数。同样,我可以扩展它来获得其他值。但是有什么方法可以在单个查询中获取所有值?

+0

要么使用UNION与每一个内部或检查采用的解决方案用于轧制和 – frlan

回答

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

惊人。非常感谢。只需在lt/gt标志处进行一些小的调整即可。 (当时(),时间间隔1年),然后1结束)last_1_yr, count(cur_timestamp = date_sub(现在(),间隔2年),然后1结束)bw_1_2_yrs, 计数(当cur_timestamp user3515684

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天的时间间隔。你可以改变你的日间隔。

0

一个可能的方法来做到这一点(未经测试,所以请原谅任何错别字)是产生一系列的时间表,并加入对你的ID表。

例如,这是给所有的罪名,逐年在过去的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') 
+0

我在'DATE_SUB (),INTERVAL sub0.interval_end YEAR)'这说:''字段列表'中的未知列'sub0.interval_end' – user3515684

+0

@ user3515684 - 正如我所说的,未经测试。希望解决这个问题。 – Kickstart