Select a sequence between two numbers on MySQL

不打扰是莪最后的温柔 提交于 2019-12-21 04:51:17

问题


I have this table named people with two dates on MySQL:

| Name | start_date | end_date   |
| John | 2007-03-01 | 2009-10-12 |
| Mike | 2001-06-06 | 2010-12-01 |

I want to create a view that lets me search by activity year, being activity year any year between the start_date and the end_date. So, I'd like to get a field with a sequence of years, like this:

| Name | activity_years                                    |
| John | 2007,2008,2009                                    |
| Mike | 2001,2002,2003,2004,2005,2006,2007,2008,2009,2010 |

I've tried some approaches, but I can't get it. Since I want to create a view, I have to do it everything inside a SELECT statement and that is giving me some headache.


回答1:


Something like this should do it:-

SELECT a.Name, GROUP_CONCAT(YEAR(DATE_ADD(a.start_date, INTERVAL b.aNum YEAR))) AS activity_years  
FROM person a
CROSS JOIN (SELECT a.i + b.i * 10 AS aNum FROM integers a, integers b) b
WHERE YEAR(DATE_ADD(a.start_date, INTERVAL b.aNum YEAR)) <= YEAR(a.end_date)
GROUP BY a.Name

It relies on a table of integers with a column called i, with the values 0 to 9. It joins this against itself to get a range of numbers from 0 to 99, so copes with date ranges that far apart.

Removing the subselects to use it in a view

SELECT p.Name, GROUP_CONCAT(YEAR(DATE_ADD(p.start_date, INTERVAL (a.i + b.i * 10) YEAR))) AS activity_years  
FROM person p
CROSS JOIN integers a
CROSS JOIN integers b
WHERE YEAR(DATE_ADD(p.start_date, INTERVAL (a.i + b.i * 10) YEAR)) <= YEAR(p.end_date)
GROUP BY p.Name



回答2:


SQLFiddle demo

select name,
       group_concat(tYears.row ORDER BY tYears.row)
  from people

join

(
SELECT @row := @row + 1 as row FROM 
(select 0 union all select 1 union all select 3 union all select 4 union all 
  select 5 union all select 6 union all select 6 union all select 7) t,
(select 0 union all select 1 union all select 3 union all select 4 union all 
  select 5 union all select 6 union all select 6 union all select 7) t2, 
(select 0 union all select 1 union all select 3 union all select 4 union all 
  select 5 union all select 6 union all select 6 union all select 7) t3, 

(SELECT @row:=1900) t21
) tYears

on tYears.row between year(start_date) and year(end_date)
group by name


来源:https://stackoverflow.com/questions/16164573/select-a-sequence-between-two-numbers-on-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!