【问题标题】:Mysql min and max values and corresponding "date" for each month每个月的 Mysql 最小值和最大值以及相应的“日期”
【发布时间】:2012-03-13 18:47:00
【问题描述】:

我有一个名为“rates”的表,它有两个字段“date”和“rate”。我喜欢获取每个月的 MIN 和 MAX 速率值及其发生日期。但我没办法。

选择日期,
MIN(rate) AS minRate,
MAX(速率) AS maxRate,
MONTH(date) AS 月份名称,
YEAR(date) AS yearName
从费率
GROUP BY yearName ASC,monthName ASC

澄清:我喜欢这样的:

 Months  MIN    mindate     MAX      maxdate  
 Jan     1.234  2012-01-13   1.534  2012-01-24  
 Feb     1.165  2012-02-28   1.373  2012-02-11  

等等

【问题讨论】:

  • 你的意思是 ORDER BY yearName ASC , monthName ASC ? GROUP BY 不需要 ASC / DESC
  • 我想在同一行获取 MIN rate 及其日期,并在同一行获取 MAX rate 及其日期。当然,我想显示所有月份的最小值和最大值。
  • 您也可以向表格提供输入吗??
  • GROUP BY yearName ASC, monthName ASC 不起作用...应该是 GROUP BY yearName, monthName ORDER BY yearName, monthName
  • @Rocky 这里不需要,因为它是默认的 ASC。但是 GROUP BY 确实可以有 DESC。在 MySQL 中,GROUP BY 意味着 ORDER BY

标签: mysql date max minimum


【解决方案1】:

试试这个查询,数据库名称是test,你可以使用你的或者删除它:

SELECT 
  MIN(rate) AS minRate,
  (select date from test.rates where rate = min(co.rate) and  
    month(date) = month(co.date) and year(date) = year(co.date) limit  
  )as min_date,
  MAX(rate) AS maxRate,
  (select date from test.rates where rate = max(co.rate) and  
    month(date) = month(co.date) and year(date) = year(co.date) limit 1) as 
  max_date
FROM test.rates co 
GROUP BY year(date) , month(date)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多