我已经研究了一些聚合和CTE帖子但是没有找到将最小值从CTE更新到附加(非CTE)外部表的解决方案。这是使用SQL 2008(Microsoft管理工作室)。我将约会表中的日期,计费表中的服务日期组合在一起,然后交叉检查患者表中的字段。如果名为“新患者日期”的字段为空,我希望使用其他两个表中最早的日期更新它。他们都加入了一个名为图表或图表编号的公共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
答案 0 :(得分: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条件)。