sql - mysql select datetime query to find ids which are 1 year old, 2 year old and so on -
i want ids created in last 1 year, or year > 1 year < 2, , on. suppose if table:
+----+--------------------------+---------------------+ | id | data                     | cur_timestamp       | +----+--------------------------+---------------------+ |  1 | time of creation is: | 2014-02-01 20:37:22 | |  2 | time of creation is: | 2015-01-01 20:37:22 | |  3 | time of creation is: | 2015-02-01 20:37:22 | |  4 | time of creation is: | 2015-12-01 20:37:22 | |  5 | time of creation is: | 2016-02-01 20:37:22 | |  6 | time of creation is: | 2016-04-01 20:37:22 | +----+--------------------------+---------------------+   i table this:
+-----------------------+-------+ | date range            | count | +-----------------------+-------+ | last 1 year           | 3     | | > 1 year & < 2 years  | 2     | | > 2 years             | 1     | +-----------------------+-------+   any content in first column fine. have count specified above. have tried various things.
select count(*) ids cur_timestamp >= date_sub(now(), interval 1 year);   this give me count of ids in last 1 year. can extend other values. there way can values in 1 single query?
this called conditional aggregation. have add more conditions many years needed.
select  count(case when cur_timestamp >= date_sub(now(), interval 1 year) 1 end) last_1_yr, count(case when cur_timestamp > date_sub(now(), interval 1 year) , cur_timestamp <= date_sub(now(), interval 2 year) 1 end) bw_1_2_yrs, count(case when cur_timestamp > date_sub(now(), interval 2 year) 1 end) gt_2_yrs ids       
Comments
Post a Comment