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

时间:2015-03-05 18:09:23

标签: sql-server subquery where-clause correlated-subquery

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

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

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行得到了na错误:

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

我希望得到以下结果:


BANK NAME |供应商名称|总合同|有效合同

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

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

提前致谢!

1 个答案:

答案 0 :(得分:0)

从你的小组中删除不同的并使用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