如何在联合列SQL上使用MIN

时间:2018-09-26 09:18:58

标签: sql postgresql count union min

我在sql中使用MIN函数时遇到问题。我想从我的计数函数中获取所有具有最小值的行的列表。

这是我的代码:

SELECT land, MIN(count) as lowest 
FROM 
 (
   SELECT temp.land, count(*) 
   FROM 
    (
      SELECT grans.land FROM Grans
      UNION ALL
      SELECT grans.aland FROM Grans
    ) as temp
   GROUP BY land
   ORDER BY land
 )  as subQuery
GROUP BY land
ORDER BY land

目前,我只得到一张列出土地和土地的表,尽管将计数重命名为最低。

2 个答案:

答案 0 :(得分:0)

如果只希望min,则删除group by,因为如果将group by放进去,它将返回您在子查询中获得的所有土地计数,因为计数已经将其归为group了,所以与众不同

SELECT * 
FROM 
 (
   SELECT temp.land, count(*) as cnt
   FROM 
    (
      SELECT grans.land FROM Grans
      UNION ALL
      SELECT grans.aland FROM Grans
    ) as temp
   GROUP BY land
   ORDER BY land
 )  as subQuery

order by cnt asc
Limit 1

另一种方法是

SELECT temp.land, count(*) as cnt
       FROM 
        (
          SELECT grans.land FROM Grans
          UNION ALL
          SELECT grans.aland FROM Grans
        ) as temp
       GROUP BY land
       having cnt in(

    SELECT min(cnt)
        FROM 
         (
           SELECT temp.land, count(*) as cnt
           FROM 
            (
              SELECT grans.land FROM Grans
              UNION ALL
              SELECT grans.aland FROM Grans
            ) as temp
           GROUP BY land
           ORDER BY land
         )  as subQuery
       )

它也可以工作

select * from
(
 SELECT * ,row_number() over(partition by land order by cnt) as rn 
    FROM 
     (
       SELECT temp.land, count(*) as cnt
       FROM 
        (
          SELECT grans.land FROM Grans
          UNION ALL
          SELECT grans.aland FROM Grans
        ) as temp
       GROUP BY land
       ORDER BY land
     )  as subQuery
 ) t where t.rn=1

答案 1 :(得分:0)

我将使用窗口功能:

SELECT land, cnt
FROM (SELECT temp.land, count(*) as cnt,
             MIN(count(*)) OVER () as min_cnt
      FROM (SELECT grans.land FROM Grans
            UNION ALL
            SELECT grans.aland FROM Grans
           ) temp
      GROUP BY land
     ) l
WHERE cnt = min_cnt;