2011-03-18 82 views
1

我絞盡腦汁廣泛搜索以找到解決方案,並且我懷疑我可能沒有清楚地詢問問題,請耐心等待。SQL查詢根據組中缺少值來過濾記錄

我必須建立幾個查詢,在以下基礎上篩選記錄。儘管涉及提取數據的多個表格我會堅持基本要求。

以下是樣本值:

Key | Decision 
123 | Complete 
123 | Additional info 
123 | Something 
123 | Complete 
. 
. 
. 
254 | Complete 
254 | Complete 
254 | Complete 
. 
. 
. 

基於上述數據,我可以通過按鍵和決策做了選擇和組得到的數據進行如下設置:

Key | Decision 
123 | Complete 
123 | Additional info 
123 | Something 
. 
. 
. 
254 | Complete 
. 
. 
. 

實際我需要的數據有兩種類型(這些是必須建立的分離查詢)

1)唯一的決定是「完成」的鍵 - 在上面的例子中,只有鍵= 254會匹配
2)關鍵決定可能包含「附加信息」 - 在上面的例子中只有鍵= 123將匹配

這似乎幾乎可能,就像我有答案在某處浮動,我不能完全理解它。還是這種一廂情願的想法?

我曾嘗試以下

select key from table where decision not in (select key from table where decision <> "Complete") 

這讓我想決策的結果=完整。但是,最終的選擇至少包含至少三個連接,我懷疑性能會變差。查詢將在Oracle 11g上執行。

如果有人有任何建議可以幫助我擺脫這種想法,我會深表感謝。

+0

我不明白。 '這些查詢將在Oracle 11g'上執行。那你爲什麼用'mysql'標籤來標記問題呢?這是一個錯誤還是標籤實際相關? – 2011-03-18 13:52:20

回答

1

對於第一個問題

select `key` from your_table 
group by key 
having count(decision) = sum(decision="complete") 

爲第二個

select `key` from your_table 
where decision = 'Additional Info' 
group by `key` 
0

1)鍵,其中只有判定爲 「完成」 - 在上面的例子僅重點= 254將匹配

select key 
    from table 
group 
    by key 
having min(decision) = 'Complete' 
    and max(decision) = 'Complete' 

或@nick rulez用以下修改ication(使它在Oracle運行以及):

having count(decision) = sum(case when decision = 'Complete' then 1 else 0 end) 

2)鍵,其中決定可能含有 「附加信息」 - 在上面的例子中唯一的關鍵= 123將匹配

select distinct key 
    from table 
where decision = 'Additional info';