I've got the following SELECT statement, and based on what I've seen here: SQL Select Max Date with Multiple records I've got my example set up the same way. I'm on Oracle 11g. Instead of returning one record for each asset_tag, it's returning multiples. Not as many records as in the source table, but more than (I think) it should be. If I run the inner SELECT statement, it also returns the correct set of records (1 per asset_tag), which really has me stumped.
SELECT
outside.asset_tag,
outside.description,
outside.asset_type,
outside.asset_group,
outside.status_code,
outside.license_no,
outside.rentable_yn,
outside.manufacture_code,
outside.model,
outside.manufacture_vin,
outside.vehicle_yr,
outside.meter_id,
outside.mtr_uom,
outside.mtr_reading,
outside.last_read_date
FROM mp_vehicle_asset_profile outside
RIGHT OUTER JOIN
(
SELECT asset_tag, max(last_read_date) as last_read_date
FROM mp_vehicle_asset_profile
group by asset_tag
) inside
ON outside.last_read_date=inside.last_read_date
Any suggestions?
Try with analytical functions:
I think you need to add...
...to the criteria in your
ON
list.Also a
RIGHT OUTER JOIN
is not needed. AnINNER JOIN
will give the same results (and may be more efficicient), since there will be cannot be be combinations ofasset_tag
andlast_read_date
in the subquery that do not exist inmp_vehicle_asset_profile
.Even then, the query may return more than one row per asset tag if there are "ties" -- that is, multiple rows with the same
last_read_date
. In contrast, @Lamak's analytic-based answer will arbitrarily pick exactly one row this situation.Your comment suggests that you want to break ties by picking the row with highest
mtr_reading
for thelast_read_date
.You could modify @Lamak's analyic-based answer to do this by changing the
ORDER BY
in theOVER
clause to:If there are still ties (that is, multiple rows with the same
asset_tag
,last_read_date
, andmtr_reading
), the query will again abritrarily pick exactly one row.You could modify my aggregate-based answer to break ties using highest
mtr_reading
as follows:If there are still ties (that is, multiple rows with the same
asset_tag
,last_read_date
, andmtr_reading
), the query may again return more than one row.One other way that the analytic- and aggregate-based answers differ is in their treatment of nulls. If any of
asset_tag
,last_read_date
, ormtr_reading
are null, the analytic-based answer will return related rows, but the aggregate-based one will not (because the equality conditions in the join do not evaluate toTRUE
when a null is involved.