mysql 求两个数之间,在MySQL上选择两个数字之间的序列

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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值