我在查询报告中无法计算。我有一个table client
和loanaccount
,其中客户端有LASTNAME
和ENCODEDKEY(PK)
行,通过名为loanaccount
的行连接到ACCOUNTHOLDERKEY
表。我一直想要计算ACCOUNTHOLDERKEY
表格中有多少loanaccount
与ENCODEDKEY(PK)
我的查询代码:
SELECT client.LASTNAME
client.ENCODEDKEY,
loanaccount.ACCOUNTHOLDERKEY,
COUNT(loanaccount.ACCOUNTHOLDERKEY) AS LOANCOUNT
FROM client
INNER JOIN loanaccount ON
client.ENCODEDKEY = loanaccount.ACCOUNTHOLDERKEY
ORDER BY LASTNAME ASC
我的查询输出:(Source以防万一。)
LASTNAME ENCODEDKEY LOANCOUNT
Yulo 8a8e8be6109ff9501610c46a6a601c7 1364
它计算所有ACCOUNTHOLDERSKEY
s,应为1.谢谢。
答案 0 :(得分:1)
您的原始查询对我来说不正确。您应该通过ENCODEDKEY
表格中的client
进行汇总,然后计算该密钥的数量:
SELECT
c.ENCODEDKEY,
c.LASTNAME,
COUNT(la.ACCOUNTHOLDERKEY) AS cnt
FROM client c
LEFT JOIN loanaccount la
ON c.ENCODEDKEY = la.ACCOUNTHOLDERKEY
GROUP BY
c.ENCODEDKEY
ORDER BY
c.LASTNAME
请注意,我将client
左连接到loanaccount
,然后计算后一个表中的ACCOUNTHOLDERKEY
字段。如果ENCODEDKEY
中的某个client
与loanaccount
表格中的任何内容不匹配,则会向我们计算零。