Sql 寻找不同的值
我正在使用Access。 我有以下疑问Sql 寻找不同的值,sql,ms-access,Sql,Ms Access,我正在使用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 AN
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的预测是相同的,我希望它只返回一条记录。目前,如果预测是相同的,那么它将显示所有这些记录。我只想让它为每一条显示一条记录
我尝试了distinct,但它似乎不起作用,并且输出是相同的
样本数据
Inst instrument prediction
16 BassSaxophone 0.9
16 B-flatclarinet 0.9
理想的输出是显示这两条记录中的一条,sql将自动选择其中一条,而不是同时显示两条记录。例如
Inst instrument prediction
16 BassSaxophone 0.9
您可以这样重写查询:
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))
);
这里还有另一个答案:DISTINCT不起作用,因为记录是不同的。如果您希望每个inst和prediction都有一个结果行,那么可以按inst和prediction分组
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;
不过,我更喜欢我的另一个答案:-)你能用样本数据和期望的结果编辑你的问题吗?“我不明白你想要的输出是什么。”戈登林诺夫编辑,希望这更有意义