Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT MAX of COUNT

I have a table "well". It contains a column app_rate_unit (type: nvarchar). My goal is to count every distinct value in the table and let the DBMS (MS Server 2005) give me the most occurring one.

This is my code:

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

The poblem with it is however, that my DBMS actually delivers the lowest count to me.

SideQuestion: How do I filter for a foreign key (in the table) and NOT NULL (in app_rate_unit) when counting?

like image 869
Rufus Avatar asked Jul 25 '12 09:07

Rufus


1 Answers

select top 1 app_rate_unit, count(*) from dbo.well
group by app_rate_unit
order by count(*) desc
like image 82
stb Avatar answered Oct 06 '22 06:10

stb