2

我研究了许多聚合和 CTE 帖子,但没有找到将最小值从 CTE 更新到附加(非 CTE)外部表的解决方案。这是使用 SQL 2008(微软管理工作室)。我将约会表中的日期、计费表中的服务日期组合在一起,然后将这些日期与患者表中的字段进行交叉检查。如果名为 New Patient Date 的字段为空白,我想使用其他两个表中的最早日期对其进行更新。他们都加入了一个称为图表或图表编号的通用 ID。这是代码...任何见解?

WITH New_Patients (chart_nbr, First_Visit)
  AS
  ( SELECT A.[Chart], MIN(A.[Appt Date])
      FROM Appointment AS A, Patient AS P
      WHERE A.[Chart] = P.[Chart Number]
        AND A.[Appt Date] IS NOT NULL
      GROUP BY A.[Chart]

   UNION

   SELECT BD.[Chart], MIN(BD.[Service Date 1])
    FROM [Billing Detail] AS BD, Patient AS P 
    WHERE BD.[Chart] = P.[Chart Number]
      AND [Transaction Code] IN 
         ('99201', '99202', '99203', '99204', '99205', '99211', '99212', '99213', 
         '99214', '99215', '99241', '99242', '99243', '99244', '97001', '97002')
      AND BD.[Service Date 1] IS NOT NULL
    GROUP BY BD.[Chart]

   UNION

   SELECT P.[Chart Number], P.[New Patient Date]
     FROM Patient AS P
     GROUP BY P.[New Patient Date], P.[Chart Number]  )

UPDATE [Patient]    
SET Patient.[New Patient Date]=MIN(First_Visit)
FROM Patient AS P, New_Patients AS NP
WHERE P.[Chart Number] = NP.chart_nbr
    AND P.[New Patient Date]IS NULL
4

1 回答 1

0

干杯,如果我的理解是正确的,我将解决以下问题:

   WITH New_Patients (chart_nbr, First_Visit)
  AS
  ( SELECT A.[Chart] as chart_nbr, MIN(A.[Appt Date]) as First_Visit
      FROM Appointment AS A, Patient AS P
      WHERE A.[Chart] = P.[Chart Number]
        AND A.[Appt Date] IS NOT NULL
      GROUP BY A.[Chart]
   UNION
   SELECT BD.[Chart], MIN(BD.[Service Date 1])
    FROM [Billing Detail] AS BD, Patient AS P 
    WHERE BD.[Chart] = P.[Chart Number]
      AND [Transaction Code] IN 
         ('99201', '99202', '99203', '99204', '99205', '99211', '99212', '99213', 
         '99214', '99215', '99241', '99242', '99243', '99244', '97001', '97002')
      AND BD.[Service Date 1] IS NOT NULL
    GROUP BY BD.[Chart]
   UNION
   SELECT P.[Chart Number], P.[New Patient Date]
     FROM Patient AS P
     GROUP BY P.[New Patient Date], P.[Chart Number]  
 )
UPDATE P SET P.[New Patient Date] = ISNULL(P.[New Patient Date], MIN(NP_group.First_Visit))
from [Patient] P 
left join 
(   
    select min[First_date) as First_Visit, chart_nbr
        from New_Patients 
            group by chart_nbr

) NP_group ON P.[Chart Number] = NP_group.chart_nbr

WITH 部分保持不变,UPDATE 部分稍作修改。在子查询中,您获得跨 CTE 表的最小日期,然后更新适用的位置(ISNULL 条件)。

于 2012-10-24T14:45:03.623 回答