简体   繁体   中英

SQL Group By with an Order By Latest on another column

I know this question has been asked a dozen times, but I have tried different solutions from each and none of them are solving the issue I am facing.

I have the following query:

SELECT mn.meter_name, m.meter_number, m.meter_location, r.rates_meter_rate, 
   r.rates_meter_PPD, m.meter_ID, mt.metertracking_periodend, 
   mt.metertracking_read, mt.metertracking_readend 
FROM db_meters m, db_meters_name mn, db_rates_meter r, db_meters_tracking mt 
WHERE m.ICP_ID = '$ICP' AND m.meter_name_ID = mn.meter_name_ID 
  AND r.meter_ID = m.meter_ID AND r.contract_ID = '$contract_ID' 
  AND mt.meter_ID = m.meter_ID 
GROUP BY meter_ID 
ORDER BY ABS( DATEDIFF( metertracking_periodend, NOW() ) )

But it is not quite doing what it is supposed to. It was hoping that it would show the latest metertracking_periodend to the current date, but instead, as there are multiple entries for the metertracking table per meter, it is showing the first inserted.

I have tried changing it to:

ORDER BY metertracking_periodend DESC

But it outputs the same, it seems to be something with the GROUP BY meter_ID, which I need as I only want the latest result per meter, of which there could be up to four.

So if someone could help me output the information ordered by the latest "metertracking_periodend" it would be appreciated. Thanks.

EDIT: OUTPUT 在此处输入图片说明

the "metertracking_periodend" actual has an entry for "2013-10-01" so this is what should be taken from the table, not the older entry of 2012-12-31. Hope this edit helps.

Try this:

SELECT mn.meter_name, m.meter_number, m.meter_location, r.rates_meter_rate, 
    r.rates_meter_PPD, m.meter_ID, mt.metertracking_periodend,
    mt.metertracking_read, mt.metertracking_readend 
FROM db_meters m, db_meters_name mn, db_rates_meter r, db_meters_tracking mt 
WHERE m.ICP_ID = '$ICP' AND m.meter_name_ID = mn.meter_name_ID 
AND r.meter_ID = m.meter_ID AND r.contract_ID = '$contract_ID' 
AND mt.meter_ID = m.meter_ID
AND metertracking_periodend = (
    select max(metertracking_periodend) 
    from db_meters_tracking
    where meter_ID = mt.meter_ID
    group by meter_ID
)
ORDER BY metertracking_periodend

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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