在相关子查询中使用 WHERE 时出错

Error when using WHERE in Correlated Subquery

我有以下关系:银行 -> 融资 -> 合同 -> 供应商

我必须 select 与供应商相关的所有银行,使用以下查询:

SELECT DISTINCT A.Name AS BankName, A2.Name as SupplierName
FROM Companies A
INNER JOIN Financing F ON F.IdFinancialCompany = A.Id
INNER JOIN Contracts C ON F.IdContract = C.Id
INNER JOIN Companies A2 ON C.IdSupplier = A2.Id
GROUP BY A.Name, A2.Name

到目前为止,还不错。

现在我必须列出活跃的合同数量和总合同数量,所以我考虑包括一个子查询:

SELECT DISTINCT A.Name AS BankName, A2.Name as SupplierName,
(SELECT COUNT(C.Id)),
(SELECT COUNT(C.Id) WHERE C.ContractStatus = 1)
FROM Companies A
INNER JOIN Financing F ON F.IdFinancialCompany = A.Id
INNER JOIN Contracts C ON F.IdContract = C.Id
INNER JOIN Companies A2 ON C.IdSupplier = A2.Id 
GROUP BY A.Name, A2.Name

第 2 行运行良好,但第 3 行出现错误:

列 'Contracts.ContractStatus' 在 select 列表中无效,因为它未包含在聚合函数或 GROUP BY 子句中。

我希望得到以下结果:


银行名称 |供应商名称 |合同总数 |有效合同

银行 1 |供应商 1| 5 | 2

我怎样才能做到这一点?我正在使用 SQL Server 2014

提前致谢!

从您的分组依据中删除不同的项并使用 CASE

SELECT A.Name AS BankName, A2.Name as SupplierName,
COUNT(C.Id),
SUM(CASE WHEN C.ContractStatus = 1 THEN 1 ELSE 0 END) 
FROM Companies A
INNER JOIN Financing F ON F.IdFinancialCompany = A.Id
INNER JOIN Contracts C ON F.IdContract = C.Id
INNER JOIN Companies A2 ON C.IdSupplier = A2.Id 
GROUP BY A.Name, A2.Name