You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL技术问题:统计存在有效LeadSource的Account中Lead Source为Null的记录数

统计符合条件的空LeadSource记录数量

需求明确:统计Accounts表中,同一Account ID下存在非空LeadSource记录的前提下,LeadSource为Null的记录总数量。

方案一:子查询筛选关联

先找出所有存在非空LeadSource的Account ID,再统计这些ID下的空值记录:

SELECT COUNT(*) AS null_leadsource_count
FROM Accounts
WHERE "Account ID" IN (
    SELECT DISTINCT "Account ID"
    FROM Accounts
    WHERE LeadSource IS NOT NULL
)
AND LeadSource IS NULL;

注:如果你的Account ID字段名带空格,需根据数据库语法用对应符号包裹(比如MySQL用反引号`Account ID`,PostgreSQL用双引号)。

方案二:窗口函数一次性计算

用窗口函数标记每个Account ID是否存在非空LeadSource,再过滤统计:

WITH AccountLeadStatus AS (
    SELECT 
        "Account ID",
        LeadSource,
        -- 标记当前Account ID是否存在非空LeadSource
        MAX(CASE WHEN LeadSource IS NOT NULL THEN 1 ELSE 0 END) OVER (PARTITION BY "Account ID") AS has_non_null_lead
    FROM Accounts
)
SELECT COUNT(*) AS null_leadsource_count
FROM AccountLeadStatus
WHERE has_non_null_lead = 1
AND LeadSource IS NULL;

注意事项

  • 如果需要统计的是符合条件的Account ID数量而非记录数,将COUNT(*)替换为COUNT(DISTINCT "Account ID")
  • 确保数据库语法适配(比如部分数据库不支持CTE,可改用子查询嵌套实现相同逻辑)

内容的提问来源于stack exchange,提问作者Lucas Lira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:35:33