0

我想同时获得特定值的最小值,以及具有该最小值的行的键。目前,我这样做如下:

SELECT dates.date AS Date, num_apples.apples AS MinApples FROM
(
    SELECT date, MIN(apples) AS MinApples, apples
    FROM Table
    HAVING MinApples = apples
) AS dates
JOIN
(
    SELECT date, apples
    FROM Table
) AS num_apples
ON (
    dates.date = num_apples.date
);

仅使用“标准”(我的意思是通常实现的)SQL 是否有更好的方法来做到这一点?

4

3 回答 3

1

我总是这样做:

SELECT *
FROM the_table
WHERE apples = (SELECT MIN(apples) 
                  FROM the_table);

但也许我错过了一些东西。

于 2013-10-09T21:57:12.330 回答
1

这是 ANSI 标准 SQL:

select *
from (
  select date, 
         apples, 
         min(apples) over () as min_apples
  from the_table
) t
where apples = min_apples;

窗口函数可用于各种 DBMS。

于 2013-10-09T21:44:44.853 回答
1

假设这date是您的关键:

SELECT qryNumApples.* FROM
(
    SELECT MIN(apples) AS MinApples
    FROM Table
) AS qryMinApples
JOIN
(
    SELECT *
    FROM Table
) AS qryNumApples
ON qryMinApples.MinApples= qryNumApples.apples
);
于 2013-10-09T21:48:07.317 回答