gpt4 book ai didi

sql-server - SQL 查询不返回相关记录处于非事件状态的记录

转载 作者:行者123 更新时间:2023-12-03 21:02:11 24 4
gpt4 key购买 nike

我有三个帐户 ABC、DEF 和XYZ。ABC 有两个 Inactive Contracts。DEF 没有任何契约(Contract)。XYZ 有两份契约(Contract)(一份有效,一份无效)。

以下查询返回如下输出。

╔════╦══════════════╦══════╗
║name║ accountId ║Count ║
╠════╬══════════════╬══════╣
║DEF ║ 554-050-4876 ║ 0 ║
║XYZ ║ 111-000-4345 ║ 1 ║
╚════╩══════════════╩══════╝

但我期待的结果如下:

╔════╦══════════════╦══════╗
║name║ accountId ║Count ║
╠════╬══════════════╬══════╣
║ABC ║ 244-5677-444 ║ 0 ║
║DEF ║ 554-050-4876 ║ 0 ║
║XYZ ║ 111-000-4345 ║ 1 ║
╚════╩══════════════╩══════╝

意思是,查询应该返回所有Accounts以及活跃Contracts的数量。如果一个帐户不存在契约(Contract),或者只有不活跃的契约(Contract)是他们的。查询应在 Count 列中返回 0。

SELECT 
a.name
, a.accountid
, COUNT(c.contractid) AS 'Count' --Number Active Of Contracts
FROM FilteredAccount AS a
LEFT OUTER JOIN FilteredContract AS c
ON a.accountid = c.accountid
WHERE a.statecode = 0 -- Active
AND a.customertypecode = 3 -- Active
AND a.name IN ('ABC','XYZ')
AND (c.statecode = 2 or c.statecode is null)
GROUP BY a.name , a.accountid;

提前致谢。

最佳答案

将所有 JOIN 条件移动到 ON 子句中:目前您在 WHERE 中有过滤条件覆盖您的 左外连接

例如

SELECT 
a.name
, a.accountid
, COUNT(c.contractid) AS 'Count' --Number Active Of Contracts
FROM FilteredAccount AS a
LEFT OUTER JOIN FilteredContract AS c
ON (c.statecode = 2 or c.statecode is null) and a.accountid = c.accountid
WHERE a.statecode = 0 -- Active
AND a.customertypecode = 3 -- Active
AND a.name IN ('ABC','XYZ')
GROUP BY a.name , a.accountid;

关于sql-server - SQL 查询不返回相关记录处于非事件状态的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25310655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com