![](/img/trans.png)
[英]how to order by count when joining another table and using 2 fields to count
[英]How can I COUNT rows from another table using a SELECT statement when joining?
这是我第一次尝试在select语句中包含行数。 我尝试了以下操作,但显然不允许以COUNT(other row)
的方式进行操作。 如何在select语句中包括另一个表的行数,主要由第一个表的对象组成?
-谢谢
...
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
。 每当聚合( 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
一些其他文档 。
您需要一个group by子句。
加:
GROUP BY
Reports.ReportID,
EmployeeADcontext,
ReportName,
CreatedDate,
ReportTotal,
Status
您可以使用子查询来返回计数。 这样,您不需要任何连接。 例如:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.