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

多表统计用户表单提交数量的SQL查询问题

问题分析与解决方案

现有查询的问题

第一种查询的缺陷

  • 仅返回表单提交数量,缺少需求要求的LoginID和FormName字段,不符合输出格式
  • 硬编码PatientApplicationId=10,只能统计单个用户,无法覆盖所有用户
  • 重复关联PatientPortalLogins表,代码冗余

第二种查询的缺陷

  • 多表INNER JOIN会产生笛卡尔积:如果用户同时有多个不同表单的记录,join后行数会是各表记录数的乘积,导致COUNT结果远大于实际提交量
  • 输出为列式结构(每个表单对应一列),不符合需求的行式结构(每个表单对应一行)
  • GROUP BY子句包含不必要的字段(cip.PatientApplicationId、cb.PatientApplicationId),会导致分组逻辑错误

正确的SQL实现

通过对每个表单表单独统计用户提交量,再用UNION ALL合并结果,完美匹配需求的输出格式:

-- 统计BurnOut表单的用户提交量
SELECT 
    l.LoginID,
    'BurnOut' AS FormName,
    COUNT(b.PatientApplicationId) AS NumberOfForms
FROM PatientPortalLogins l
LEFT JOIN Client_BurnOuts b ON l.PatientApplicationId = b.PatientApplicationId
GROUP BY l.LoginID

UNION ALL

-- 统计EmergencyAssistances表单的用户提交量
SELECT 
    l.LoginID,
    'EmergencyAssistances' AS FormName,
    COUNT(ea.PatientApplicationId) AS NumberOfForms
FROM PatientPortalLogins l
LEFT JOIN Client_EmergencyAssistances ea ON l.PatientApplicationId = ea.PatientApplicationId
GROUP BY l.LoginID

UNION ALL

-- 统计DukeEnergyFoundations表单的用户提交量
SELECT 
    l.LoginID,
    'DukeEnergyFoundations' AS FormName,
    COUNT(du.PatientApplicationId) AS NumberOfForms
FROM PatientPortalLogins l
LEFT JOIN Client_DukeEnergyFoundations du ON l.PatientApplicationId = du.PatientApplicationId
GROUP BY l.LoginID

UNION ALL

-- 统计CIPEnergyCrisises表单的用户提交量
SELECT 
    l.LoginID,
    'CIPEnergyCrisises' AS FormName,
    COUNT(cip.PatientApplicationId) AS NumberOfForms
FROM PatientPortalLogins l
LEFT JOIN Client_CIPEnergyCrisises cip ON l.PatientApplicationId = cip.PatientApplicationId
GROUP BY l.LoginID

可选调整

  • 如果仅需要统计有提交记录的用户,将所有LEFT JOIN替换为INNER JOIN即可
  • 如果需要统计单个用户,在每个子查询的GROUP BY前添加WHERE l.PatientApplicationId = 10

内容的提问来源于stack exchange,提问作者Mizanur Rahaman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:25:24