如何选择MAX(日期时间)行并获取列的最小值?

时间:2016-05-29 14:42:41

标签: mysql

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

我想选择具有最大日期的所有塔,然后对于那些塔我还想要表中的最小容量值。

结果将是:

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

我拥有的是这个,但它并不总能给出正确的最小值。

SELECT npc.*, groupedcap.MinCapacity
FROM np_capacity npc
INNER JOIN
(SELECT tower, MAX(date) AS MaxDate
FROM np_capacity
GROUP BY tower) groupednpc 
ON npc.tower = groupednpc.tower 
INNER JOIN 
(SELECT tower, MIN(capacity) AS MinCapacity
FROM np_capacity
GROUP BY tower) groupedcap 
ON npc.tower = groupedcap.tower 
AND npc.date = groupednpc.MaxDate

3 个答案:

答案 0 :(得分:2)

您可以使用子选择来计算最小容量和最大日期。然后,与表连接以获取其他字段。

select npc.*, calc.minCapacity
from (
    select tower, max(datetime) maxDate, min(capacity) minCapacity
    from np_capacity
    group by tower
) calc
join np_capacity npc on (npc.tower = calc.tower
                         and npc.datetime = npc.maxDate)

此请求选择所有塔,并为每个塔选择maxdatetime和mincapacity。

如果您只想要具有maxdatetime的塔,您可以使用:

select npc.*, (select min(c2.capacity) from np_capacity c2 
               where c2.tower = npc.tower) minCapacity
from (select max(datetime) maxDatetime from np_capacity) c1
join np_capacity npc on (npc.datetime = c1.maxDatetime)

答案 1 :(得分:0)

SELECT `a`.`id`,`a`.`tower`,`a`.`datetime`,`a`.`capacity`,(SELECT MIN(`b`.`capacity`) 
FROM `np_capacity` `b` WHERE `b`.`tower`=`a`.`tower` ) AS `MinCapacity` FROM `np_capacity` `a` 
WHERE `a`.`datetime`=(SELECT MAX(`datetime`) FROM `np_capacity`);

SQL Fiddle

上测试上述查询

答案 2 :(得分:0)

另一个答案是在子查询中使用order by和limit 1:

select t1.*,(select capacity from np_capacity t3 
  where t1.tower=t3.tower 
  order by capacity limit 1) mincapacity  
  from np_capacity t1 where  
 datetime=(select datetime from np_capacity
  order by datetime desc limit 1);

sqlfiddle

上测试