计算每月的记录数

时间:2016-11-02 16:53:26

标签: mysql sql

我有包含开始日期和结束日期的记录,如下所示:

id  start_date   end_date
1   2016-01-01   2016-10-31
2   2016-06-01   2016-12-31
3   2016-06-01   2016-07-31

我必须知道每月活跃的记录数量(或更好的放置:在给定时期内所有月份的第一天)。计算2016年时,计数看起来像这样:

jan: 1
feb: 1
mar: 1
apr: 1
may: 1
jun: 3
jul: 3
aug: 2
sep: 2
oct: 2
nov: 1
dec: 1

我提出的解决方案是创建一个TEMP TABLE,其中包含给定时期内的所有适用日期:

date
2016-01-01
2016-02-01
...

这使查询变得非常简单:

SELECT
  COUNT(*),
  m.date
FROM
  months m
INNER JOIN table t
  ON m.date BETWEEN t.start_date AND t.end_date
GROUP BY
  m.date

这恰好产生了我正在寻找的结果。然而;我觉得这样做可以更轻松。我只是不知道如何。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

你可以通过以下方式实现,即使它看起来很难看:

假设您要运行报告并且您只对“特定年份的月份”感兴趣,则以下查询可能有效:

select m,Count(id) FROM (
SELECT 1 as m UNION 
SELECT 2 as m UNION 
SELECT 3 as m UNION 
SELECT 4 as m UNION 
SELECT 5 as m UNION 
SELECT 6 as m UNION 
SELECT 7 as m UNION 
SELECT 8 as m UNION 
SELECT 9 as m UNION 
SELECT 10 as m UNION 
SELECT 11 as m UNION 
SELECT 12 as m) AS tabseq
CROSS JOIN x WHERE 
  (year (start_date) = 2016 AND year (end_date) = 2016 AND m >= month(start_date) AND m <= month(end_date)) -- starts abd ends this year
  or
  (year (start_date) < 2016 AND year (end_date) = 2016 AND m <= month(end_date)) -- ends this year, consider months until end of contract
  or
  (year (start_date) < 2016 AND year (end_date) > 2016) -- spans the year, ignore month,
  or
  (year (start_date) = 2016 AND year (end_date) > 2016 AND m >= month(start_date)) -- starts this year, consider months until end of year
GROUP BY m;

结果:

m   count(id)
1   1
2   1
3   1
4   1
5   1
6   3
7   3
8   2
9   2
10  2
11  1
12  1

答案 1 :(得分:0)

正如评论中所建议的那样,我将临时表替换为名为&#39; calendar&#39;的永久表。

CREATE TABLE `calendar` (
  `date` date NOT NULL,
  PRIMARY KEY (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

我在这张桌子上填写了2000-01-01至2100-12-31的所有日期。我重写了我的查询:

SELECT
  COUNT(*),
  c.date
FROM
  calendar c
INNER JOIN table t
  ON c.date BETWEEN t.start_date AND t.end_date
WHERE
  DAYOFMONTH(c.date) = 1
AND
  c.date BETWEEN '2016-01-01' AND '2016-12-31'
GROUP BY
  c.date