繁体   English   中英

选择具有MAX(datetime)的行,并且还获得带有列日期的min值?

[英]Select rows with MAX(datetime) and also get min values with their dates for a column?

我的表是这样的(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

到目前为止一切都很好。 datetime用于max(datetime),而MinCapacity是过去两周的最小值,也是我想要的。 我如何也可以为选定的MinCapacity获取特定的日期时间。 (MinCapacityDate)

您可以尝试一下,如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;

您可能需要加入和在哪里

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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM