Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting no of rows returned by a select query

I need to count the no of rows which is returned by the following query.

select m.Company_id from Monitor as m     inner join Monitor_Request as mr on mr.Company_ID=m.Company_id     group by m.Company_id     having COUNT(m.Monitor_id)>=5 

I have tried with following

select COUNT(*) from ( select m.Company_id from Monitor as m     inner join Monitor_Request as mr on mr.Company_ID=m.Company_id     group by m.Company_id     having COUNT(m.Monitor_id)>=5)   

It gives an error message in query analyzer which says the following:

Msg 102, Level 15, State 1, Line 7 Incorrect syntax near ')'.

like image 576
Joshua Avatar asked Mar 30 '12 15:03

Joshua


People also ask

How do I count the number of rows returned by a query in SQL?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

How do I count a query in a selection?

The COUNT (*) function returns the number of rows that satisfy the WHERE clause of a SELECT statement. The following example finds how many rows in the stock table have the value HRO in the manu_code column: SELECT COUNT(*) FROM stock WHERE manu_code = 'HRO';

How do you get the number of rows affected by a query?

MySQL ROW_COUNT() can be used to get the total number of rows affected by MySQL query. To illustrate it we are creating a procedure with the help of which we can insert records in a table and it will show us how many rows have been affected.


2 Answers

SQL Server requires subqueries that you SELECT FROM or JOIN to have an alias.

Add an alias to your subquery (in this case x):

select COUNT(*) from ( select m.Company_id from Monitor as m     inner join Monitor_Request as mr on mr.Company_ID=m.Company_id     group by m.Company_id     having COUNT(m.Monitor_id)>=5)  x 
like image 180
JNK Avatar answered Sep 18 '22 17:09

JNK


Try wrapping your entire select in brackets, then running a count(*) on that

select count(*) from (    select m.id    from Monitor as m      inner join Monitor_Request as mr         on mr.Company_ID=m.Company_id   group by m.Company_id     having COUNT(m.Monitor_id)>=5 ) myNewTable 
like image 30
Mikey Mouse Avatar answered Sep 17 '22 17:09

Mikey Mouse