SELECT MAX的COUNT

时间:2012-07-25 09:13:08

标签: sql sql-server-2005 count max

我有一张桌子“好”。它包含一列app_rate_unit(类型:nvarchar)。 我的目标是计算表中的每个不同值,让DBMS(MS Server 2005)给我最多的值。

这是我的代码:

SELECT MAX(app_rate_unit) AS MAX_APP
  FROM (SELECT app_rate_unit, COUNT(*) AS co
          FROM dbo.well AS w
         GROUP BY app_rate_unit
        ) AS derivedtbl_1
然而,与此有关的问题是,我的DBMS实际上向我提供了最低的数量。

SideQuestion:在计数时如何过滤外键(在表中)和NOT NULL(在app_rate_unit中)?

4 个答案:

答案 0 :(得分:15)

select top 1 app_rate_unit, count(*) from dbo.well
group by app_rate_unit
order by count(*) desc

答案 1 :(得分:1)

试试这个

    SELECT 
        COUNT(app_rate_unit)AS MAX_APP , 
        app_rate_unit 
    FROM 
        dbo.well
    WHERE
            app_rate_unit IS NOT NULL
    GROUP BY 
        app_rate_unit 
    ORDER BY 
            MAX_APP DESC

上面的脚本会给你计数和项目。如果您不确定只有一个项目具有最大出现次数,则可以更改计数。

答案 2 :(得分:0)

select top 1 count(*) as co from dbo.well as w group by app_rate_unit
order by count(*) desc

答案 3 :(得分:0)

在PostgreSQL中,我们可以使用max of count as

编写查询
select max(count) from (

select count(id) from Table _name group by created_by,status_id having status_id = 6 ) as Alias

例如

select max(count) from (

select count(id) from orders group by created_by,status_id having status_id = 6 ) as foo