我可以在单个查询中获取与聚合相关的数据吗?

时间:2013-10-09 21:41:05

标签: sql

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

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?

3 个答案:

答案 0 :(得分:1)

这是ANSI标准SQL:

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

窗口函数可用于各种DBMS。

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

答案 2 :(得分:1)

我总是这样做:

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

但也许我错过了什么。