我使用以下查询:
select MONITOR_ALERT_INSTANCE_ID as Id
, description
, created_date
from monitor_alert_instance
where description in(
select distinct(description)
from monitor_alert_instance
where co_mod_asset_id=1223
group by description
)
,输出结果为:
如何根据最新(日期和时间)获得结果,该结果将在结果集中显示三个不同的值。预期的输出是:
+----------------------------------+---------------------------------------+--
| 766 | Test..... | 14-03-04 14:56:51.000000000 |
| 765 | Water_pH_sensor_malfunction | 14-03-04 13:55:04.000000000 |
| 762 | Water_turbidity_meter_malfunction | 14-03-04 13:54:33.000000000 |
+----------------------------------+---------------------------------------+--
由于
答案 0 :(得分:1)
您可以使用聚合获得您想要的结果:
select max(MONITOR_ALERT_INSTANCE_ID) as Id, description, max(created_date) as created_date
from monitor_alert_instance
where description in (select description
from monitor_alert_instance
where co_mod_asset_id = 1223
)
group by description;
请注意,我简化了子查询。使用distinct
时group by
是多余的。使用in
时也不一定。
编辑:
我认为您可以使用此查询获得相同的结果:
select max(MONITOR_ALERT_INSTANCE_ID) as Id, description, max(created_date) as created_date
from monitor_alert_instance
group by description
having max(case when co_mod_asset_id = 1223 then 1 else 0 end) = 1;
having
子句确保说明适用于资产1223
。
哪种表现更好取决于许多因素,但这可能比in
版本表现更好。 (或者表格可能足够小,以至于任何性能差异都可以忽略不计。)
答案 1 :(得分:0)
select id,
description,
created_date
from (
select MONITOR_ALERT_INSTANCE_ID as Id,
description
created_date,
row_number() over (partition by description order by created_date desc) as rn
from monitor_alert_instance
where co_mod_asset_id = 1223
) t
where rn = 1