我需要计算以下查询返回的行数。
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
我尝试了以下
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)
它在查询分析器中给出了一条错误消息,其中包含以下内容:
Msg 102,Level 15,State 1,Line 7')'附近的语法不正确。
答案 0 :(得分:54)
SQL Server要求您SELECT FROM
或JOIN
的子查询具有别名。
为子查询添加别名(在本例中为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
答案 1 :(得分:9)
尝试将整个选择包装在括号中,然后在该
上运行计数(*)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
答案 2 :(得分:5)
语法错误仅仅是由于子查询缺少别名:
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) mySubQuery /* Alias */
答案 3 :(得分:0)
select COUNT(*)
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