簡體   English   中英

計算每月的記錄數

[英]Count the number of records per month

我有開始日期和結束日期的記錄,如下所示:

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

這將產生我正在尋找的結果。 然而; 我確實覺得這可以更輕松地完成。 我就是不知道

有什么建議么?

即使看起來很丑,也可以通過以下方式進行操作:

假設您要運行報告,並且只對“某年的月份”感興趣,則以下查詢可能有效:

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

如評論中所建議,我將臨時表替換為名為“ calendar”的永久表。

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

我用2000年1月1日至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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM