如何从子查询中计数(*)

时间:2013-05-27 16:08:46

标签: sql sql-server

如何使用子查询编写计数(*)?

select count(*) from Firms
select count(*) from (select * from Firms)

在上面的两行中,顶部的一行有效,但在第二行,我得到错误:

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

但不是(select * from Firms) == Firms

修改 但是为此:

select count(*) from 
    (
        select HireResponseID, HireResponse, DateResponse, Comments, YearFileOpened, file_number, isCaseOpen, last_update, isConfidential, date_created, OurClient, TheirClient, ProjectName, description, lawyer_lastname, lawyer_firstname, Conflicts.ConflictID
        from Hire_Response, Conflicts, Lawyers 
        WHERE Hire_Response.ConflictID=Conflicts.ConflictID AND Lawyers.lawyerID=Conflicts.lawyerID AND firmID = @FirmID AND HireID = @HireID AND isStillaConflict = 1 
        ORDER BY  file_number, TheirClient, OurClient, lawyer_lastname, lawyer_firstname
    ) as data

我收到错误:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您在第二个版本上缺少别名:

select count(*) 
from 
(
  select * -- change this to the column names - you shouldn't use select *
  from Firms
) f -- this is missing

SQL Server需要在所有派生表和子查询上使用别名