2014-11-06 46 views
0

我正在使用Access。 我有以下查詢;查找不同的值

SELECT instruments.inst , instruments.predicted, instruments.prediction 
FROM instruments 
INNER JOIN 
(SELECT inst, MAX(prediction) AS [predictions] 
FROM instruments 
GROUP BY inst) groupedtt 
ON instruments.inst = groupedtt.inst 
AND instruments.prediction = groupedtt.predictions 

我想要做的是,如果INST的預測是相同的,我希望它只返回一條記錄。目前如果預測結果相同,則會顯示所有這些記錄。我只想要它爲每個顯示一個記錄。

我試過不同的,但它似乎沒有工作,並且輸出是相同的。

樣本數據

Inst instrument  prediction 
16 BassSaxophone  0.9 
16 B-flatclarinet  0.9 

希望的輸出將顯示的這兩個記錄之一,SQL自動選擇其中的一個,而不是同時顯示的記錄。例如。

Inst instrument  prediction 
16 BassSaxophone  0.9 
+0

你能有樣本數據和預期的效果編輯您的問題嗎?我不明白你想要輸出的是什麼。 – 2014-11-06 12:41:25

+0

@GordonLinoff editied,希望這會更有意義 – zebby 2014-11-06 12:52:29

回答

0

這是給你另外一個答案:DISTINCT不起作用,因爲記錄是不同的。如果你想要一個結果行 inst和預測,你 inst和預測。

SELECT instruments.inst , MAX(instruments.predicted), instruments.prediction 
FROM instruments 
INNER JOIN 
(SELECT inst, MAX(prediction) AS [predictions] 
FROM instruments 
GROUP BY inst) groupedtt 
ON instruments.inst = groupedtt.inst 
AND instruments.prediction = groupedtt.predictions 
GROUP BY instruments.inst , instruments.prediction; 

我喜歡對方的回答更好,雖然:-)

1

你可以這樣重寫查詢:

select inst, predicted, prediction 
from instruments i1 
where not exists 
(
    select * 
    from instruments i2 
    where i2.inst = i1.inst 
    and i2.prediction > i1.prediction 
); 

即獲得所有儀器都不存在相同的儀器並且具有更大的預測。

現在我們只需要擴展where子句就可以獲得每個預測的一條記錄。

select inst, predicted, prediction 
from instruments i1 
where not exists 
(
    select * 
    from instruments i2 
    where i2.inst = i1.inst 
    and (i2.prediction > i1.prediction or 
     (i2.prediction = i1.prediction and i2.instrument > i1.instrument)) 
);