2017-02-24 92 views
0

我有一个表是这样的:累积值在MySQL

Tournament Name  Start    End 
Chess A    2016-12-14  2017-01-31 
Football B   2016-08-01  2017-02-15 
.... 

我需要创建一个表,会告诉我每月正在进行比赛的数量。例如:

Month-Year Number of ongoing Tournaments 
01-2016   2 
02-2016   3 
... 
12-2016   4 

有什么建议吗? 感谢

回答

1

可以生成月份列表,然后使用join或相关子查询:

select date_format(month_start, '%Y-%m') as yyyymm, 
     (select count(*) 
     from tournaments t 
     where t.start <= m.month_start and 
       t.end >= m.month_start + interval 1 month 
     ) as ongoing 
from (select date('2016-01-01') as month_start union all 
     select date('2016-02-01') as month_start 
    ) m; 

注:这只是计数的比赛是适用于整个月。如果您希望部分月份锦标赛进行计数,您可以调整where条款。

+0

但是,如果我需要从2016-01-01开始的所有月份,我需要写下类似于(select date('2016-01-01')as month_start union all select date('2016-02-01 ')作为MONTH_START UNION ALL 选择日期(' 2016年3月1日 ')为MONTH_START UNION ALL ... 选择日期(' 2016年12月1' 日)为MONTH_START )M 吧? –

+0

@JoseCabreraZuniga。 。 。是。您可以将所需的月份添加到“m”。 –