我研究了许多聚合和 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