如何在我的sql函数中使用max(count(*)?

vfhzx4xs  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(433)
SELECT F.origin, F.destination, COUNT(DISTINCT E.ename), COUNT(F.flno)
FROM Flights F, Employees E, Certified C, Aircraft A
WHERE E.eid = C.eid AND E.salary > 100000 AND A.aid = C.aid AND F.distance >= A.cruisingrange
GROUP BY E.ename, F.origin, F.destination
HAVING (COUNT(F.flno)) = 14

问题是 14max(count(F.flno)) 但我不知道如何把这些都转换成那个 14 基于的最大列数 COUNT(F.flno)

0pizxfdo

0pizxfdo1#

有一种方法可以做到这一点,在SQLServer中,在其他数据库中,您可以检查顶级的等价项。

with source_qry
   as(
    SELECT F.origin, F.destination, COUNT(DISTINCT E.ename), COUNT(F.flno) as cnt_flno
      FROM Flights F, 
           Employees E, 
           Certified C, 
           Aircraft A
     WHERE E.eid = C.eid 
       AND E.salary > 100000 
       AND A.aid = C.aid 
       AND F.distance >= A.cruisingrange
    GROUP BY E.ename, F.origin, F.destination
         )
select top 1* 
  from source_qry
order by cnt_flno desc
vshtjzan

vshtjzan2#

SELECT F.origin, F.destination, COUNT(DISTINCT E.ename), COUNT(F.flno)
FROM Flights F, Employees E, Certified C, Aircraft A
WHERE E.eid = C.eid AND E.salary > 100000 AND A.aid = C.aid AND F.distance >= A.cruisingrange
GROUP BY E.ename, F.origin, F.destination
ORDER BY 4 DESC
LIMIT 1;
7kqas0il

7kqas0il3#

WITH data AS (
    SELECT F.origin, F.destination, COUNT(DISTINCT E.ename) AS cnt_ename, COUNT(F.flno) AS cnt,
        MAX(COUNT(F. flno)) OVER () AS maxcnt
    FROM Flights F, Employees E, Certified C, Aircraft A
    WHERE E.eid = C.eid AND E.salary > 100000 AND A.aid = C.aid AND F.distance >= A.cruisingrange
    GROUP BY E.ename, F.origin, F.destination
)
SELECT * FROM data WHERE cnt = maxcnt;

这将处理最大数量的领带。摆脱使用的习惯 top 以及 limit 不加区别地。

相关问题