sql-serversql-server-2008t-sql

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 ')'.


Solution

  • 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