2

我有一张这样的桌子:

ID_____StartDate_____EndDate
----------------------------
1______05/01/2012___02/03/2013
2______06/30/2013___07/12/2013
3______02/17/2010___02/17/2013
4______12/10/2012___11/16/2013

我正在尝试计算每年活跃的 ID。如果 ID 已激活多年,则会被计算多次。我不想将年份“硬编码”到我的查询中,因为数据是多年的。(即不能使用CASE YEAR(StartDate) WHEN x then yIF...

上表的期望结果:

YEAR_____COUNT
2010_____1
2011_____1
2012_____3
2013_____4

我试过了:

SELECT COUNT(ID)
FROM table
WHERE (DATE_FORMAT(StartDate, '%Y-%m') BETWEEN '2013-01' AND '2013-12'
    OR DATE_FORMAT(EndDate, '%Y-%m') BETWEEN '2013-01' AND '2013-12')

当然,这只适用于 2013 年。我也尝试过:

SELECT YEAR(StartDate) AS 'Start Year', YEAR(EndDate) AS 'End Year', COUNT(id)
FROM table
WHERE StartDate IS NOT NULL
GROUP BY YEAR(StartDate);

尽管这给了我在给定年份开始的那些。

4

1 回答 1

2

假设有一个辅助表包含从 1 .. 到 X 的连续数字(其中 X 必须大于表中可能的年数):

create table series( x int primary key auto_increment );
insert into series( x )
select null from information_schema.tables;

那么查询可能如下所示:

SELECT years.year, count(*)
FROM (
   SELECT mm.min_year + s.x - 1 as year
   FROM (
      SELECT min( year( start_date )) min_year, 
             max( year( end_date )) max_year
      FROM tab
   ) mm
   JOIN series s
   ON s.x <= mm.max_year - mm.min_year + 1
   GROUP BY  mm.min_year + s.x - 1
) years
JOIN tab
ON years.year between year( tab.start_date )
                  and year( tab.end_date )
GROUP BY years.year
;

看一个演示:http ://www.sqlfiddle.com/#!2/f49ab/14

于 2013-10-15T21:20:40.250 回答