我的表就像这样(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获取特定的日期时间。 (MinCapacityDate)
答案 0 :(得分:1)
您可以尝试这一点,在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;
答案 1 :(得分:0)
您是否需要加入和
中的位置select a.*, b.min(capacity)
from np_capacity as a
where a.tower, datetime in (
select tower, max(datetime)
from np_capacity
group by tower)
inner join np_capacity as b on a.tower = b.tower
group by a.id, a.tower, a.datetime