如何从子查询返回多个字段

时间:2019-02-19 17:46:55

标签: sql sql-server-2008

我在医疗保健部门工作,我们在此检查患者的保险,以了解他们的保险是否仍然有效并且有资格获得我们的服务。不幸的是,该数据库不能很好地将资格与约会或将来的访问相关联(我们对此无法控制)。结果,我们无法了解资格检查的最终结果(我们是否使用了这种保险?患者根本没有使用保险吗?等等)。

我们要做的是尝试在资格检查的当天(即当天或前一天)内将资格与患者的就诊关联起来。我想检索该访问号和该次访问的主要付款人(我希望访问该访问号,以便可以验证自己是否进行了正确的访问以及正确的主要付款人)。

如何在主要查询的结果中同时获得这两条信息?替代方法:如果我仅从内联子查询返回付款人姓名,如何才能检查结果以验证其是否正常工作?

资格查询

select distinct
  elig.patient_id,
  pm.payer_name,
  elig.status,
  elig.reject_reason
from
  eligibility elig
  inner join payer_mstr pm on elig.payer_id=pm.payer_id
where
  elig.create_timestamp>='2019-01-01' and elig.create_timestamp<'2019-02-01'

关联的付款人和付款人数据和表格

select distinct
  pe.enc_nbr,
  pm.payer_name
from
  patient_encounter pe --visit data
--encounter_payer holds payer data for a specific visit, and 1 means primary payer
  left join encounter_payer epay on pe.enc_id=epay.enc_id and cob=1 
  left join payer_mstr pm on epay.payer_id=pm.payer_id

我正在使用Microsoft SQL Server 2008 R2

2 个答案:

答案 0 :(得分:0)

很难测试您的具体问题,但是请尝试以下操作:

SELECT DISTINCT
    elig.patient_id,
    pm.payer_name,
    elig.status,
    elig.reject_reason
    pe.enc_nbr
FROM
    patient_encounter pe
    LEFT JOIN encounter_payer epay on pe.enc_id=epay.enc_id and cob=1 
    LEFT JOIN payer_mstr pm on epay.payer_id=pm.payer_id
    LEFT JOIN eligibility elig on elig.payer_id=pm.payer_id
WHERE
    elig.create_timestamp>='2019-01-01' and elig.create_timestamp<'2019-02-01'

答案 1 :(得分:0)

您可以尝试使用公用表表达式。就像子查询一样,您可以从中添加所有想要的字段。

Common Table Expressions

WITH cte AS (
	select 
	  pe.enc_nbr,
	  pm.payer_name,
	  pm.payer_id,
	  ROW_NUMBER() OVER(PARTITION BY pm.payer_id ORDER BY pm.payer_id ASC) AS row_num --If you have a date created on each row I would change the pm.payer_id field that and change it to ORDER BY <field> DESC
	from
	  patient_encounter pe --visit data
	--encounter_payer holds payer data for a specific visit, and 1 means primary payer
	  left join encounter_payer epay on pe.enc_id=epay.enc_id and cob=1 
	  left join payer_mstr pm on epay.payer_id=pm.payer_id
	--Here you could add a WHERE clause to narrow your search date down to get previous or current date if you have a date field just use WHERE date >= DATEADD(d,-1,GETDATE())
)
select distinct
  elig.patient_id,
  pm.payer_name,
  elig.status,
  elig.reject_reason,
  cte.enc_nbr
from
  eligibility elig
  inner join payer_mstr pm on elig.payer_id=pm.payer_id
  left join cte ON cte.pm.payer_id = pm.payer_id --Now you can pull in any fields you need and can see if they have a record or do not
where
  elig.create_timestamp>='2019-01-01' and elig.create_timestamp<'2019-02-01'