2014-11-06 21 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)) 
);