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

如何在SQL Server中针对不同条件复用同表同列生成SSRS报表

解决SSRS报表中复用同一张表列获取多条件数据的SQL写法

针对你的需求,核心是处理键值对结构表转结构化列的场景(即同一列存储不同类型的属性值,通过条件区分),下面提供两种常用的SQL实现方案,适配你提到的PatientInfoDB数据库结构:

前提假设(若结构不符可调整)

  • Patients表为主表,包含PatientID(主键)、PatientName、PatientRegNo、AttendingEmployeeID(关联负责员工的ID)字段
  • Params表为患者属性表,通过PatientID关联Patients,包含ParamType(属性类型,如'Gender'、'BloodGroup')、ParamValue(属性值)字段
  • EmployeeInfo表包含EmployeeID(主键)、Designation、WorkPlace字段

方案1:多次JOIN同一张属性表

通过多次左关联Params表,每次指定不同的属性类型条件,直接映射为目标列:

SELECT 
    p.PatientName,
    p.PatientRegNo,
    gender.ParamValue AS Gender,
    bloodGroup.ParamValue AS BloodGroup,
    e.Designation,
    e.WorkPlace
FROM PatientInfoDB.dbo.Patients p
-- 关联获取性别
LEFT JOIN PatientInfoDB.dbo.Params gender
    ON p.PatientID = gender.PatientID
    AND gender.ParamType = 'Gender'
-- 关联获取血型
LEFT JOIN PatientInfoDB.dbo.Params bloodGroup
    ON p.PatientID = bloodGroup.PatientID
    AND bloodGroup.ParamType = 'BloodGroup'
-- 关联员工表获取职称和工作地点
LEFT JOIN PatientInfoDB.dbo.EmployeeInfo e
    ON p.AttendingEmployeeID = e.EmployeeID

方案2:条件聚合(更适合多属性场景)

使用CASE WHEN配合聚合函数(如MAX),在一次关联中提取多类型属性值,性能更优:

SELECT 
    p.PatientName,
    p.PatientRegNo,
    -- 按属性类型过滤,提取对应值
    MAX(CASE WHEN pr.ParamType = 'Gender' THEN pr.ParamValue END) AS Gender,
    MAX(CASE WHEN pr.ParamType = 'BloodGroup' THEN pr.ParamValue END) AS BloodGroup,
    e.Designation,
    e.WorkPlace
FROM PatientInfoDB.dbo.Patients p
LEFT JOIN PatientInfoDB.dbo.Params pr
    ON p.PatientID = pr.PatientID
LEFT JOIN PatientInfoDB.dbo.EmployeeInfo e
    ON p.AttendingEmployeeID = e.EmployeeID
-- 按患者及员工字段分组,确保每个患者仅返回一行
GROUP BY p.PatientName, p.PatientRegNo, e.Designation, e.WorkPlace

扩展适配场景

如果Designation/WorkPlace也存储在Params/SysParams表中,只需扩展对应逻辑:

  • 方案1:新增对应条件的JOIN语句
  • 方案2:新增CASE WHEN分支

如果SysParams是系统字典表(存储属性字典,如性别代码对应文本),则需要先关联Params到SysParams:

SELECT 
    p.PatientName,
    p.PatientRegNo,
    gender_sp.ParamValue AS Gender,
    bg_sp.ParamValue AS BloodGroup,
    e.Designation,
    e.WorkPlace
FROM PatientInfoDB.dbo.Patients p
LEFT JOIN PatientInfoDB.dbo.Params gender_p
    ON p.PatientID = gender_p.PatientID AND gender_p.ParamType = 'Gender'
LEFT JOIN PatientInfoDB.dbo.SysParams gender_sp
    ON gender_p.ParamCode = gender_sp.ParamCode
LEFT JOIN PatientInfoDB.dbo.Params bg_p
    ON p.PatientID = bg_p.PatientID AND bg_p.ParamType = 'BloodGroup'
LEFT JOIN PatientInfoDB.dbo.SysParams bg_sp
    ON bg_p.ParamCode = bg_sp.ParamCode
LEFT JOIN PatientInfoDB.dbo.EmployeeInfo e
    ON p.AttendingEmployeeID = e.EmployeeID

内容的提问来源于stack exchange,提问作者Mehedi Hasan Kajol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:27:19