SQL - 选择具有最大值的所有行

时间:2012-07-08 08:13:28

标签: mysql sql greatest-n-per-group

我有这个SQL查询:

SELECT id, COUNT(*) AS price
FROM (SELECT * FROM rt WHERE somecondition) AS st
      JOIN tt
      ON st.id = tt.id
GROUP BY id;

现在,我想选择具有该表最高价格的所有行。我试过这个,遗憾的是根本没有返回任何行:

SELECT id, COUNT(*) AS price
FROM (SELECT * FROM rt WHERE somecondition) AS st
      JOIN tt
      ON st.id = tt.id
GROUP BY id
HAVING price = MAX(price);

我有点失落,有人有任何指示吗?

6 个答案:

答案 0 :(得分:3)

对我来说这看起来很简单:

select * from <table> 
where <column name> in(
   SELECT MAX(column name) FROM table
)

答案 1 :(得分:1)

试试这个解决方案:

SELECT a.id, a.price
FROM
(
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa
    INNER JOIN tt bb ON aa.id = bb.id
    WHERE aa.somecondition
    GROUP BY aa.id
) a
INNER JOIN
(
    SELECT MAX(aa.price) AS maxprice
    FROM
    (
        SELECT COUNT(1) AS price
        FROM rt aaa
        INNER JOIN tt bbb ON aaa.id = bbb.id
        WHERE aaa.somecondition
        GROUP BY aaa.id
    ) aa
) b ON a.price = b.maxprice

编辑:虽然我想不出任何重写方法,以便不必冗余地编写基本查询,但 可以 或许这样做:

SELECT GROUP_CONCAT(a.id) AS ids, a.price
FROM
(
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa
    INNER JOIN tt bb ON aa.id = bb.id
    WHERE aa.somecondition
    GROUP BY aa.id
) a
GROUP BY a.price
ORDER BY a.price DESC
LIMIT 1

这将生成以逗号分隔的id,这些id共享相同的最大值。这可能不是您正在寻找的格式,但 是一种避免必须编写两次基本查询的方法。把它放在那里。

答案 2 :(得分:0)

HAVING用于在聚合发生后检查条件。

在聚合发生之前使用

WHERE

SELECT id, COUNT(*) AS price
FROM (SELECT * FROM rt WHERE somecondition) AS st
  JOIN tt
  ON st.id = tt.id
WHERE price = (SELECT MAX(price) FROM ...table)
GROUP BY id

答案 3 :(得分:0)

试试这个,把MAX放入选中,这应该是正确的方法

SELECT id, COUNT(*) AS price, MAX(price) AS max_price
FROM (SELECT some_table_name FROM rt WHERE somecondition LIMIT 1) AS st
      JOIN thenextTable as tt
      ON st.id = tt.id
GROUP BY id;

答案 4 :(得分:0)

假设@ Zane的答案是你想要的,这里是他的查询的可移植版本,也避免了LIMIT / TOP操作。我对mysql方言并不熟悉,但我认为这样可以毫无问题地工作。

SELECT a.id, a.price
FROM (
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa
    INNER JOIN tt bb ON aa.id = bb.id
    WHERE [somecondition]
    GROUP BY aa.id
) a
WHERE
    a.price >= ALL (
        SELECT COUNT(1) AS maxprice
        FROM rt aa
        INNER JOIN tt bb ON aa.id = bb.id
        WHERE [somecondition]
        GROUP BY aa.id
    )

答案 5 :(得分:0)

您要求的方法不需要多次声明内部查询的冗余。这肯定是cte的好处。这是另外两个使用这种策略重写的解决方案。

WITH basequery as (
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa INNER JOIN tt bb ON aa.id = bb.id
    WHERE [aa.somecondition]
    GROUP BY aa.id
)
SELECT a.id, a.price
FROM
    basequery as a INNER JOIN
    (SELECT MAX(price) AS maxprice FROM basequery) as b
        ON a.price = b.maxprice
-- or
WITH basequery as (
    SELECT aa.id, COUNT(1) AS price
    FROM rt aa INNER JOIN tt bb ON aa.id = bb.id
    WHERE [aa.somecondition]
    GROUP BY aa.id
)
SELECT a.id, a.price
FROM
    basequery as a
WHERE
    a.price >= ALL (SELECT price FROM basequery)