2012-07-25 107 views
7

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

这是我的代码:

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 

与它poblem然而,我的DBMS的实际投放量最低计数我。

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

回答

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

如果有多个行具有相同的最大计数,那么我们应该如何编写一个查询来选择所有具有最大计数的顶部行,而不是仅选择顶部1? – 2014-12-05 16:40:40

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

作品查询,但我不想让计数值,但值的名称,发生得最多。你有任何关于我构成的SideQuestion的意见吗? – Rufus 2012-07-25 09:30:08

+0

我想他想要得到最高计数的app_rate_unit,而不是计数本身。看看我的发言。 – stb 2012-07-25 09:30:29

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 

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

+0

就像一个魅力。它怎么不计数NULL值,但是stb的声明呢? – Rufus 2012-07-25 09:36:08

+0

可能是因为NULL不大于任何其他值。 但我已明确添加NULL检查条件。检查编辑的脚本。 – Narendra 2012-07-25 09:38:44

+0

啊是的,...对。看到有点晚了,对不起 – Rufus 2012-07-25 09:39:40

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