使用 MAX() 从同一行获取数据?
Get data from same row with MAX()?
[MariaDB 10.4,PHP8.0]
我如何重写它才能使其工作,以便它从具有 MAX(total_weight) 的行中 获取 weight_date 并将其列为 highest_weight_date?我读到我们不能在 WHERE 中使用 MAX()?
我已经测试过重写几个例子,但是我放弃了并且不好意思展示我最近的尝试:
weight_date HAVING total_weight=MAX(total_weight) AS highest_weight_date
我尝试将其添加到此,但出现错误。
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=9c057570bd60cdf20a7148189a77fdc4
SELECT *
, LEAD(total_weight, 1) OVER(
ORDER BY weight_date DESC
) AS prev_total_weight
, LEAD(weight_date, 1) OVER(
ORDER BY weight_date DESC
) AS prev_total_weight_date
, MIN(total_weight) OVER() AS lowest_weight
, MAX(total_weight) OVER() AS highest_weight
, FROM_UNIXTIME(weight_date, '%u') AS weight_week
, ROW_NUMBER() OVER(
ORDER BY weight_date DESC
) AS RowNum
FROM (
SELECT *, weight_start_week + weight_end_week AS total_weight
FROM YourTable
) t
ORDER BY RowNum
谢谢
要获得 highest_weight_date(具有最高 total_weight 的行中的 weight_date),您只需添加到 select:
FIRST_VALUE(weight_date) OVER (ORDER BY total_weight DESC) AS highest_weight_date
尽管我建议您执行 ORDER BY total_weight DESC, weight_date
或 ORDER BY total_weight DESC, weight_date DESC
,这样当权重出现在多个日期时,您可以确定地获得具有该权重的第一个或最后一个日期,而不是任意日期。
I have read that we can't use MAX() among with WHERE?
也许这有帮助:使用子查询在 WHERE 子句中查找 MAX() 权重。使用您的示例数据 ...
select from_unixtime( weight_date )
from YourTable
where ( weight_start_week + weight_end_week ) = (
select max( weight_start_week + weight_end_week )
from YourTable
) ;
-- result
from_unixtime( weight_date )
2022-01-14 00:00:00
[MariaDB 10.4,PHP8.0] 我如何重写它才能使其工作,以便它从具有 MAX(total_weight) 的行中 获取 weight_date 并将其列为 highest_weight_date?我读到我们不能在 WHERE 中使用 MAX()? 我已经测试过重写几个例子,但是我放弃了并且不好意思展示我最近的尝试:
weight_date HAVING total_weight=MAX(total_weight) AS highest_weight_date
我尝试将其添加到此,但出现错误。 https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=9c057570bd60cdf20a7148189a77fdc4
SELECT *
, LEAD(total_weight, 1) OVER(
ORDER BY weight_date DESC
) AS prev_total_weight
, LEAD(weight_date, 1) OVER(
ORDER BY weight_date DESC
) AS prev_total_weight_date
, MIN(total_weight) OVER() AS lowest_weight
, MAX(total_weight) OVER() AS highest_weight
, FROM_UNIXTIME(weight_date, '%u') AS weight_week
, ROW_NUMBER() OVER(
ORDER BY weight_date DESC
) AS RowNum
FROM (
SELECT *, weight_start_week + weight_end_week AS total_weight
FROM YourTable
) t
ORDER BY RowNum
谢谢
要获得 highest_weight_date(具有最高 total_weight 的行中的 weight_date),您只需添加到 select:
FIRST_VALUE(weight_date) OVER (ORDER BY total_weight DESC) AS highest_weight_date
尽管我建议您执行 ORDER BY total_weight DESC, weight_date
或 ORDER BY total_weight DESC, weight_date DESC
,这样当权重出现在多个日期时,您可以确定地获得具有该权重的第一个或最后一个日期,而不是任意日期。
I have read that we can't use MAX() among with WHERE?
也许这有帮助:使用子查询在 WHERE 子句中查找 MAX() 权重。使用您的示例数据 ...
select from_unixtime( weight_date )
from YourTable
where ( weight_start_week + weight_end_week ) = (
select max( weight_start_week + weight_end_week )
from YourTable
) ;
-- result
from_unixtime( weight_date )
2022-01-14 00:00:00