这是我第一次尝试在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
答案 0 :(得分:3)
您错过了GROUP BY
。每当您汇总(SUM
,COUNT
,MAX
等)时,您始终需要包含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