2014-03-04 46 views
0

我使用下面的查詢:如何獲得Oracle中使用SQL的不同值結果

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 
        ) 

,並輸出結果是:

enter image description here

我怎樣才能根據結果最新的(日期和時間)將在結果集中顯示三個不同的值。預期的輸出是:

+----------------------------------+---------------------------------------+-- 
| 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

'distinct'是**不是**的函數。 'distinct(description)'和'distinct description'之間沒有區別。或者換句話說,它與'select description'和'select(description)'之間的區別是相同的。無論如何,'distinct'對於用於'IN'運算符的子查詢來說都沒有意義。最後:在同一列上''by ** **和**'distinct'根本沒有任何意義。 –

回答

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; 

注意,我簡化了子查詢。當使用group by時,distinct是多餘的。當使用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版本更好。 (或者表格可能足夠小,以至於性能上的差異可以忽略不計。)

+0

謝謝。兩種解決方案都像魅力一樣運作。 :-) – Novis

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 
+0

我應該在哪裏傳遞co_mod_asset_id = 1223? – Novis

+0

在子查詢中。 – Zane

+0

你能告訴我我該怎麼做。現在有點困惑。 – Novis

相關問題