Oracle在多条记录上选择最大日期

时间:2012-05-25 21:37:09

标签: sql oracle select subquery max

我已经获得了以下SELECT语句,并基于我在此处看到的内容:SQL Select Max Date with Multiple records我的示例设置方式相同。我是关于Oracle 11g的。它不是为每个asset_tag返回一条记录,而是返回多个。没有源表中的记录多,但超过(我认为)它应该是。如果我运行内部SELECT语句,它也会返回正确的记录集(每个asset_tag 1个),这真的让我感到难过。

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

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

尝试分析功能:

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 (  SELECT *, ROW_NUMBER() OVER(PARTITION BY asset_tag ORDER BY last_read_date DESC) Corr
        FROM mp_vehicle_asset_profile) outside
WHERE Corr = 1

答案 1 :(得分:0)

我认为你需要添加......

AND outside.asset_tag=inside.asset_tag

...符合ON列表中的条件。

也不需要RIGHT OUTER JOININNER JOIN将给出相同的结果(并且可能更有效),因为子查询中不能存在asset_taglast_read_date的组合{{1}中不存在}}

即使这样,如果存在“关联”,则查询可能会为每个资产标记返回多行 - 即多个行具有相同的mp_vehicle_asset_profile。相比之下,@ Lamak的基于分析的答案将在这种情况下任意选择一行。

您的评论表明,您希望通过为last_read_date选择mtr_reading最高的行来打破关系。

您可以修改@ Lamak基于分析的答案,方法是将last_read_date子句中的ORDER BY更改为:

OVER

如果仍然存在关联(即多行具有相同的ORDER BY last_read_date DESC, mtr_reading DESC asset_taglast_read_date),则查询将再次无误地选择一行。

您可以使用最高mtr_reading修改基于聚合的答案以断开关系,如下所示:

mtr_reading

如果仍有联系(即多个行具有相同的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 INNER JOIN ( SELECT asset_tag, MAX(last_read_date) AS last_read_date, MAX(mtr_reading) KEEP (DENSE_RANK FIRST ORDER BY last_read_date DESC) AS mtr_reading FROM mp_vehicle_asset_profile GROUP BY asset_tag ) inside ON outside.asset_tag = inside.asset_tag AND outside.last_read_date = inside.last_read_date AND outside.mtr_reading = inside.mtr_reading asset_taglast_read_date),则查询可能会再次返回多行。

基于分析和基于聚合的答案不同的另一种方式是对空值的处理。如果mtr_readingasset_taglast_read_date中的任何一个为空,则基于分析的答案将返回相关的行,但基于聚合的行不会(因为连接中的相等条件)当涉及null时,不要评估为mtr_reading