7

我有一张“好”的桌子。它包含一个列 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

4 回答 4

15
select top 1 app_rate_unit, count(*) from dbo.well
group by app_rate_unit
order by count(*) desc
于 2012-07-25T09:29:10.070 回答
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

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

于 2012-07-25T09:32:08.403 回答
0
select top 1 count(*) as co from dbo.well as w group by app_rate_unit
order by count(*) desc
于 2012-07-25T09:24:31.710 回答
0

在 PostgreSQL 中,我们可以编写使用最大计数的查询

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
于 2014-06-03T07:11:34.770 回答