背景
我已将两个长金融交易列表(两个公司各一个)合并为一个表(实际上是一个DataView,原因并不重要)。 这两家公司与很多客户开展业务。 我想要的是一个查询,它返回每个公司与每个客户的财务交易总数。
例如:
Customer Company A Company B
Customer X 10 0
Customer Y 15 26
Customer Z 0 71
因此,每个客户至少与一家公司打交道,可能还与两家公司打交道。
到目前为止,我的查询到目前为止。 。 。
SELECT v.[Company],
v. [AnalysisName],
s1.CMTtrans,
s2.CFLtrans
FROM vMainCustTrans AS v
LEFT JOIN (SELECT [AnalysisName], COUNT([AnalysisName]) AS CMTtrans
FROM vMainCustTrans
WHERE [Company] = 'Money'
GROUP BY [AnalysisName]) AS s1
ON v.[AnalysisName] = s1.[AnalysisName]
LEFT JOIN (SELECT [AnalysisName], COUNT([AnalysisName]) AS CFLtrans
FROM vMainCustTrans
WHERE [Company] = 'Forex'
GROUP BY [AnalysisName]) AS s2
ON v.[AnalysisName] = s2.[AnalysisName]
ORDER BY v.[Company], v.[AnalysisName]
现在子查询(s1)返回89个客户 子查询(s2)返回37个客户 然而整个查询返回18,989行 应该有89到126行(即89 + 37)行,具体取决于A公司和B公司之间的重叠程度
有人可以指出我的查询有什么问题以及我如何产生我想要的结果;即客户列表,其中两个客户与两个客户中的每个客户进行的交易数量均为两个。
答案 0 :(得分:2)
如果我做对了(Customer = AnalysisName),它应该是:
SELECT
v. [AnalysisName],
SUM(CASE WHEN [Company] = 'Money' THEN 1 ELSE 0 END) CMTtrans,
SUM(CASE WHEN [Company] = 'Forex' THEN 1 ELSE 0 END) CFLtrans
FROM vMainCustTrans AS v
GROUP BY v.[AnalysisName]
ORDER BY v.[AnalysisName]