寻找不同的价值观

时间:2014-11-06 12:39:04

标签: 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
AND instruments.prediction = groupedtt.predictions

我想要做的是,如果INST的预测是相同的,我希望它只返回一条记录。目前,如果预测相同,那么它将显示所有这些记录。我想要的只是为每个显示一条记录。

我尝试过不同,但它似乎没有用,输出也是一样。

示例数据

Inst  instrument        prediction
16  BassSaxophone       0.9
16  B-flatclarinet      0.9

所需的输出将显示这两个记录之一,sql自动选择其中一个,而不是显示两个记录。 E.g。

Inst  instrument        prediction
16  BassSaxophone       0.9

2 个答案:

答案 0 :(得分: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
);

即。得到所有没有相同inst的仪器且具有更大预测的仪器。

现在每个预测只能获得一条记录,我们只需扩展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))
);

答案 1 :(得分: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;

我更喜欢我的另一个答案: - )

相关问题