Mysql

帶日期的 MIN / MAX 值

  • May 26, 2016

我正在嘗試獲取目前月份的 MAX 和 MIN 值以及這些值的日期。

我得到了 MAX 和 MIN 值,但沒有得到這些值的日期。相反,我得到了這個月的第一天。

這是我的查詢:

SELECT  DATE(CREATED) AS date
     , MIN(ROUND(AMBIENT_TEMPERATURE,1)) AS min_temp
     , MAX(ROUND(AMBIENT_TEMPERATURE,1)) AS max_temp
FROM WEATHER_MEASUREMENT
WHERE (MONTH(DATE(CREATED)) = Month(NOW()));

這就是我得到的:

date        min_temp  max_temp
----------  --------  --------
2016-05-01  17.8      43.2

我想有一個max_temp的日期和一個min_temp的日期。

我該怎麼做?

您的查詢是無效的 SQL,但 MySQL 以預設設置接受它。它會給你一個隨機的結果。您可以通過將“ONLY_FULL_GROUP_BY”添加到 sql_mode 來更改此行為。

編輯:類似於@MickyT 的解決方案,但使用連接代替:

SELECT M.*
FROM WEATHER_MEASUREMENT M
JOIN (
  SELECT MONTH(CREATED) AS MONTH
       , MIN(AMBIENT_TEMPERATURE) AS MIN_TEMP
       , MAX(AMBIENT_TEMPERATURE) AS MAX_TEMP
  FROM WEATHER_MEASUREMENT M
  GROUP BY MONTH(CREATED)
) X
   ON MONTH(M.CREATED) = X.MONTH
  AND M.AMBIENT_TEMPERATURE IN (X.MIN_TEMP, X.MAX_TEMP);

目前尚不清楚在平局的情況下應該使用什麼時間,查詢會輸出出現最低或最高溫度的所有時間。假設您希望第一次出現,例如:

SELECT MIN(M.CREATED), M.AMBIENT_TEMPERATURE
FROM WEATHER_MEASUREMENT M
JOIN (
  SELECT MONTH(CREATED) AS MONTH
       , MIN(AMBIENT_TEMPERATURE) AS MIN_TEMP
       , MAX(AMBIENT_TEMPERATURE) AS MAX_TEMP
  FROM WEATHER_MEASUREMENT M
  GROUP BY MONTH(CREATED)
) X
   ON MONTH(M.CREATED) = X.MONTH
  AND M.AMBIENT_TEMPERATURE IN (X.MIN_TEMP, X.MAX_TEMP);
GROUP BY M.AMBIENT_TEMPERATURE

可以使用。

我省略了當月的謂詞,但這很容易添加。由於 MySQL 不支持LATERAL連接,因此最好將該謂詞添加到派生表中。IE

SELECT MIN(M.CREATED), M.AMBIENT_TEMPERATURE
FROM WEATHER_MEASUREMENT M
JOIN (
  SELECT MONTH(CREATED) AS MONTH
       , MIN(AMBIENT_TEMPERATURE) AS MIN_TEMP
       , MAX(AMBIENT_TEMPERATURE) AS MAX_TEMP
  FROM WEATHER_MEASUREMENT M
  WHERE (MONTH(DATE(CREATED)) = Month(NOW()))
  GROUP BY MONTH(CREATED)
) X
   ON MONTH(M.CREATED) = X.MONTH
  AND M.AMBIENT_TEMPERATURE IN (X.MIN_TEMP, X.MAX_TEMP);
WHERE (MONTH(DATE(CREATED)) = Month(NOW()))
GROUP BY M.AMBIENT_TEMPERATURE

正如@RolandoMySQLDBA 指出的那樣,可以以更友好的索引方式重寫 WHERE 子句。

這是我對您的要求的解釋。
作為一個簡單的查詢,這將返回您想要的,但是您可能想嘗試其他選項來使其執行。我不使用 MySQL,但在 SQL Server 中,我會考慮嘗試 CROSS APPLIES 或某種分組選項。

此查詢將返回出現最小值或最大值的所有日期。然後,您當然可以對其進行過濾以適合您的需要。

SELECT *
FROM WEATHER_MEASUREMENT M
WHERE AMBIENT_TEMPERATURE IN
 (SELECT MIN(AMBIENT_TEMPERATURE) TEMP
  FROM WEATHER_MEASUREMENT L
  WHERE MONTH(L.CREATED) = MONTH(M.CREATED)
  UNION ALL
  SELECT MAX(AMBIENT_TEMPERATURE) TEMP
  FROM WEATHER_MEASUREMENT L
  WHERE MONTH(L.CREATED) = MONTH(M.CREATED)
 )

SQL小提琴

引用自:https://dba.stackexchange.com/questions/139408