gpt4 book ai didi

mysql - 选择具有 MAX(datetime) 的行并获取列的最小值及其日期?

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

我的表是这样的(np_capacity):

id  tower  datetime             capacity
---|----|---------------------|----------
1 | A | 2016-05-29 09:02:41 | 34676
2 | B | 2016-05-29 09:02:41 | 10736
5 | C | 2016-05-29 09:02:41 | 55664
3 | D | 2016-05-29 09:02:41 | 32622
4 | A | 2016-05-29 13:08:38 | 5474
6 | B | 2016-05-29 13:08:38 | 20692
7 | C | 2016-05-29 13:08:38 | 134802
8 | D | 2016-05-29 13:08:38 | 4754

这是我的查询:

SELECT npc.*,
(SELECT min(c2.capacity) FROM np_capacity c2 WHERE c2.tower = npc.tower AND datetime BETWEEN (NOW() - INTERVAL 14 DAY) AND NOW()) minCapacity,

FROM (SELECT max(datetime) maxDatetime FROM np_capacity) c1
JOIN np_capacity npc ON (npc.datetime = c1.maxDatetime)

它将选择具有最大日期时间的所有塔,然后对于这些塔,它还将选择表中过去两周的最小容量值。输出是这样的:

id  tower  datetime             capacity   MinCapacity
---|----|---------------------|----------|-------------
4 | A | 2016-05-29 13:08:38 | 5474 | 5474
6 | B | 2016-05-29 13:08:38 | 20692 | 10736
7 | C | 2016-05-29 13:08:38 | 134802 | 55664
8 | D | 2016-05-29 13:08:38 | 4754 | 4754

到目前为止一切都很好。日期时间是 max(datetime) 的,而 MinCapacity 是过去两周的最小值,也是我想要的。如何获取所选 MinCapacity 的具体日期时间。 (最小容量日期)

最佳答案

您可以尝试一下,SQLFiddle 中对此进行了演示。 。如果超过 1 行具有最小容量,则返回最近的日期。

SELECT np_capacity.id, np_capacity.tower, np_capacity.datetime
,np_capacity.capacity, mincap.mincapacity
, MAX(tmincapdatetime.datetime) AS datetimeOfMin
FROM (SELECT MAX(`datetime`) AS maxdatetime
FROM np_capacity) AS tmaxdatetime
JOIN np_capacity
ON tmaxdatetime.maxdatetime = np_capacity.`datetime`
LEFT JOIN (SELECT tower, MIN(capacity) as mincapacity
FROM np_capacity
WHERE `datetime` BETWEEN (NOW() - INTERVAL 14 DAY) AND NOW()
GROUP BY tower) AS mincap
ON mincap.tower = np_capacity.tower
LEFT JOIN np_capacity AS tmincapdatetime
ON tmincapdatetime.`datetime` BETWEEN (NOW() - INTERVAL 14 DAY) AND NOW()
AND mincap.tower = tmincapdatetime.tower
AND mincap.mincapacity = tmincapdatetime.capacity
GROUP BY np_capacity.id, np_capacity.tower, np_capacity.datetime
,np_capacity.capacity, mincap.mincapacity
ORDER BY tower;

关于mysql - 选择具有 MAX(datetime) 的行并获取列的最小值及其日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37686665/

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