0

我希望有人可以在这里帮助我。

我正在尝试在 mysql 中编写一个查询,但我很难获得正确的语法。让我解释一下我想要做什么。

我有一个表格,其中包含建筑测量数据,每个条目都有一个 location_id、room_id、measurement_value、floor_num、measurement_date。我正在尝试编写查询以获取每层楼的最新测量数据(只有两层楼)。所以我在想这样的事情,但我无法让它发挥作用。

 select bottom_floor.value as bottom_value, top_floor.value as top_value
 from 
 (select measurement_value, measurement_date, floor_num, room_id from rom_measurements where location_id = '1' and floor_num='1' order by measurement_date DESC limit 1) as bottom_floor
 Join 
 (select measurement_value, measurement_date, floor_num, room_id from rom_measurements where location_id = '1' and floor_num='2' order by measurement_date DESC limit 1) as top_floor

所以我认为这会给我两个值。我已经看到,如果两个子查询之一返回一个空集,它就不起作用,我也很确定我在这里做错了其他事情。

有人可以推荐一个更好的方法来完成这个吗?

谢谢!

4

1 回答 1

1

楼层上所有房间的总面积:

select square, measurement_date, floor_num
from room_measurements rm
join (
  select location_id, floor_num, max(measurement_date) as date, sum(measurement_value) as square
  from room_measurements 
  group by location_id, floor_num    
) rm2 
ON rm.measurement_date=rm2.date AND rm.location_id=rm2.location_id AND rm.floor_num=rm2.floor_num
WHERE location_id = '1'

地板上每个房间的正方形:

select measurement_value, measurement_date, floor_num, room_id
from room_measurements rm
join (
  select location_id, floor_num, room_id, max(measurement_date) as date
  from room_measurements 
  group by location_id, floor_num, room_id    
) rm2 
ON rm.measurement_date=rm2.date AND rm.location_id=rm2.location_id AND rm.floor_num=rm2.floor_num AND rm.room_id = rm2.room_id
WHERE location_id = '1'
于 2012-12-09T11:37:52.517 回答