如何在加入时使用SELECT语句来计算来自另一个表的行?

时间:2014-09-18 16:23:03

标签: sql tsql stored-procedures

这是我第一次尝试在select语句中包含行计数。我已尝试过以下内容,但显然不允许使用COUNT(other row)我试图这样做的方式。 如何在select语句中包含另一个表的行计数,主要由第一个表中的对象组成?

-Thanks

...

SELECT
Reports.ReportID,
EmployeeADcontext,
ReportName,
CreatedDate,
COUNT(Expenses.ExpID) AS ExpCount,
ReportTotal,
Status

FROM
[dbo].[Reports]
INNER JOIN
[dbo].[Expenses]
ON 
[dbo].[Expenses].ReportID = [dbo].[Reports].ReportID

WHERE EmployeeADcontext = @rptEmployeeADcontext

3 个答案:

答案 0 :(得分:3)

您错过了GROUP BY。每当您汇总(SUMCOUNTMAX等)时,您始终需要包含GROUP BY语句,其中包含除聚合字段之外的所有可见字段。所以你的代码应该是:

SELECT
Reports.ReportID,
EmployeeADcontext,
ReportName,
CreatedDate,
COUNT(Expenses.ExpID) AS ExpCount,
ReportTotal,
Status

FROM
[dbo].[Reports]
INNER JOIN
[dbo].[Expenses]
ON 
[dbo].[Expenses].ReportID = [dbo].[Reports].ReportID

WHERE EmployeeADcontext = @rptEmployeeADcontext

GROUP BY  Reports.ReportID, EmployeeADcontext, ReportName, CreatedDate, 
          ReportTotal,  Status

以下是T-SQL GROUP BY上的其他documentation

答案 1 :(得分:2)

您需要group by子句。

添加:

GROUP BY
    Reports.ReportID,
    EmployeeADcontext,
    ReportName,
    CreatedDate,
    ReportTotal,
    Status

答案 2 :(得分:2)

您可以使用子查询返回计数。这样你就不需要任何联接。例如:

SELECT
r.ReportID,
r.EmployeeADcontext,
r.ReportName,
r.CreatedDate,
(select COUNT(e1.ExpID) FROM Expenses e1 where e1.ReportID = r.ReportId) AS ExpCount,
r.ReportTotal,
r.Status
FROM Reports r
WHERE r.EmployeeADcontext = @rptEmployeeADcontext