gpt4 book ai didi

mysql - GROUP BY MONTH() 隐藏结果

转载 作者:行者123 更新时间:2023-11-29 04:25:29 25 4
gpt4 key购买 nike

我正在计算每个月有多少结果。

这是我的查询:

SELECT 
COUNT(*) as nb,
CONCAT(MONTH(t.date),0x3a,YEAR(t.date)) as period
FROM table1 t
WHERE t.criteria = 'value'
GROUP BY MONTH(t.date)
ORDER BY YEAR(t.date)

我的结果:

nb  period
---------------
7 6:2009
46 8:2009
2 10:2009
1 11:2009
14 1:2009
9 9:2010
161 7:2010
5 2:2010
88 3:2010
28 4:2010
4 5:2011
2 12:2011

问题是,我确定我在 5:2011 和 12:2011 之间以及其他时间段之间得到了结果自 2009 年以来……:/

这是我的请求还是mysql配置的问题?

非常感谢

最佳答案

您必须同时按年和月进行分组。否则,您 2012 年 4 月的行也会与 2011 年 4 月(和 2010 年 4 月......)的行分组。

SELECT 
COUNT(*) AS nb,
CONCAT(MONTH(t.date), ':', YEAR(t.date)) AS period
FROM table1 AS t
WHERE t.criteria = 'value'
GROUP BY YEAR(t.date)
, MONTH(t.date) ;

(您使用 0x3a 而不是 ':' 有什么原因吗?)


您还可以使用其他一些 DATE and TIME functions MySQL,因此每行调用的函数更少,查询效率可能更高:

SELECT 
COUNT(*) AS nb,
DATE_FORMAT(t.date, '%m:%Y') AS period
FROM table1 AS t
WHERE t.criteria = 'value'
GROUP BY EXTRACT( YEAR_MONTH FROM t.date) ;

对于多个查询,在您的数据库中有一个永久日历表(包含所有日期或所有年月)或什至多个日历表是很有用的。示例:

CREATE TABLE CalendarYear
( Year SMALLINT UNSIGNED NOT NULL
, PRIMARY KEY (Year)
) ENGINE = InnoDB ;

INSERT INTO CalendarYear
(Year)
VALUES
(1900), (1901), ..., (2099) ;

CREATE TABLE CalendarMonth
( Month TINYINT UNSIGNED NOT NULL
, PRIMARY KEY (Month)
) ENGINE = InnoDB ;

INSERT INTO CalendarMonth
(Month)
VALUES
(1), (2), ..., (12) ;

这些也可以帮助我们制作我们在这里需要的:

CREATE TABLE CalendarYearMonth
( Year SMALLINT UNSIGNED NOT NULL
, Month TINYINT UNSIGNED NOT NULL
, FirstDay DATE NOT NULL
, NextMonth_FirstDay DATE NOT NULL
, PRIMARY KEY (Year, Month)
) ENGINE = InnoDB ;

INSERT INTO CalendarYearMonth
(Year, Month, FirstDay, NextMonth_FirstDay)
SELECT
y.Year
, m.Month
, MAKEDATE(y.Year, 1) + INTERVAL (m.Month-1) MONTH
, MAKEDATE(y.Year, 1) + INTERVAL (m.Month) MONTH
FROM
CalendarYear AS y
CROSS JOIN
CalendarMonth AS m ;

然后您可以使用日历表来编写更复杂的查询,例如您想要的变体(缺少月份)并且可能更有效。在 SQL-Fiddle 中测试:

SELECT 
COUNT(t.date) AS nb,
CONCAT(cal.Month, ':', cal.Year) AS period
FROM
CalendarYearMonth AS cal
JOIN
( SELECT
YEAR(MIN(date)) AS min_year
, MONTH(MIN(date)) AS min_month
, YEAR(MAX(date)) AS max_year
, MONTH(MAX(date)) AS max_month
FROM table1
WHERE criteria = 'value'
) AS mm
ON (cal.Year, cal.Month) >= (mm.min_year, mm.min_month)
AND (cal.Year, cal.Month) <= (mm.max_year, mm.max_month)
LEFT JOIN
table1 AS t
ON t.criteria = 'value'
AND t.date >= cal.FirstDay
AND t.date < cal.NextMonth_FirstDay
GROUP BY
cal.Year, cal.Month ;

关于mysql - GROUP BY MONTH() 隐藏结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com