SQL:在MIN查询后询问MAX结果

时间:2017-11-19 06:20:28

标签: sql database select

我正在尝试编写一个查询,我选择具有最低Ram的PC中最高的速度。

使用此SQL语句

Select DISTINCT RAM FROM PC WHERE RAM = (Select MIN(RAM) FROM PC);

给出了这个结果:

RAM
512

使用此SQL语句

Select Speed, Ram From PC WHERE Speed = (Select Max(Speed) from PC WHERE Ram = (Select DISTINCT RAM FROM PC WHERE RAM = (Select MIN(RAM) FROM PC)));

给出这个结果

Speed RAM
3.2   512
3.2   1024

我的查询中出错了什么?第二条记录不应该显示,因为我们已经选择了Min(RAM)

示例数据:

CREATE TABLE PC (   model INT PRIMARY KEY,
                  speed NUMBER (4,2),
                  ram INT,
                        hd INT,
                  price NUMBER (7,2)
                );

INSERT INTO PC VALUES (1001, 3.66, 1024, 250, 2114);
INSERT INTO PC VALUES (1002, 2.10, 512, 250, 995);
INSERT INTO PC VALUES (1003, 1.42, 512, 80, 478);
INSERT INTO PC VALUES (1004, 2.80, 1024, 250, 649);
INSERT INTO PC VALUES (1005, 3.20, 512, 250, 630);
INSERT INTO PC VALUES (1006, 3.20, 1024, 320, 1049);
INSERT INTO PC VALUES (1007, 2.20, 1024, 200, 510);
INSERT INTO PC VALUES (1008, 2.20, 2048, 250, 770);
INSERT INTO PC VALUES (1009, 2.00, 1024, 250, 650);
INSERT INTO PC VALUES (1010, 2.80, 2048, 300, 770);
INSERT INTO PC VALUES (1011, 1.86, 2048, 160, 959);
INSERT INTO PC VALUES (1012, 2.80, 1024, 160, 649);
INSERT INTO PC VALUES (1013, 3.06, 512, 80, 529);

2 个答案:

答案 0 :(得分:2)

你过分复杂了。

要选择最小ram,您可以将语句缩短为:

SELECT MIN(RAM) FROM PC

要选择最小ram的最大速度,请使用:

SELECT MAX(speed) FROM PC where RAM = (SELECT MIN(RAM) FROM PC)

答案 1 :(得分:0)

使用分析函数并不太困难:

SELECT model, speed, ram, price
FROM
(
    SELECT model, speed, ram, price, RANK() OVER (ORDER BY speed DESC) rn2
    FROM
    (
        SELECT model, speed, ram, price, RANK() OVER (ORDER BY ram) rn1
        FROM PC
    ) t
    WHERE rn1 = 1
) t
WHERE rn2 = 1;

这种方法的优点是它返回整个匹配记录。