代码之家  ›  专栏  ›  技术社区  ›  Prometheus

Postgresql:从临时表中获取最大值?

  •  0
  • Prometheus  · 技术社区  · 4 年前

     WITH country_sold AS ( 
       SELECT l.country, sum(r.sold) as count 
       FROM Label as l, released as r 
       WHERE l.label_name = r.label_name  
       GROUP BY l.country
     )
    

    请求 SELECT * FROM country_sold; 回馈:

    Country Sold
    
    USA     3232322
    England 1232
    

    SELECT max(sold) FROM country_sold;

    它给了我返回的最大值(来自美国的值),但是我怎样才能同时检索到这个国家呢?当我尝试使用

    SELECT country, max(sold) FROM country_sold GROUP BY country; 
    

    但这只会返回country\u selled的初始结果,只是使用了不同的列名,如上所示:

    Country max
    
    USA     3232322
    England 1232
    

    2 回复  |  直到 4 年前
        1
  •  1
  •   Gordon Linoff    4 年前

    从未 在中使用逗号 FROM 总是 标准 JOIN 语法。

    就用吧 ORDER BY LIMIT :

    WITH country_sold AS (
          SELECT l.country, sum(r.sold) as count
          FROM Label l JOIN
               released r 
               ON l.label_name = r.label_name
          GROUP BY l.country
         )
    SELECT cs.*
    FROM country_sold cs
    ORDER BY count DESC
    LIMIT 1;
    

          SELECT l.country, sum(r.sold) as count
          FROM Label l JOIN
               released r 
               ON l.label_name = r.label_name
          GROUP BY l.country
          ORDER BY count DESC
          LIMIT 1
    
        2
  •  1
  •   Chananel P    4 年前

    看到了吗 here postgresql文档中的示例:

    SELECT city FROM weather
    WHERE temp_lo = (SELECT max(temp_lo) FROM weather)
    

    SELECT country FROM country_sold
    WHERE sold = (SELECT max(sold) FROM country_sold)