SQL 服务器 INSERT INTO 特殊

SQL Server INSERT INTO special

我有一个问题,非常感谢您的帮助。

我有 4 个 tables:

我需要用来自 tables ABPHolter 和 [=19= 的 DISTINCT HISID 填充 PatientList table ],还有 LastNameFirstNameMiddleName 以及最近的 ScanDateandTime 进入 LastVisit 列。

例如:

ABP table 有

ID001, Doe, John, William, 2018-06-01 15:00
ID001, Doe, John, William, 2018-06-05 12:00
ID002, Parson, Rob, Michael, 2018-05-03 11:35
ID002, Parson, Rob, Michael, 2018-04-20 19:30

正在休息table有

ID001, Doe, John, William, 2018-04-01 11:11
ID003, Andersen, Pamela, Erwin, 2018-06-20 20:00

动态心电图 table 有

ID002, Parson, Rob, Michael, 2018-05-30 11:00
ID001, Doe, John, William, 2018-06-28 12:45
ID003, Andersen, Pamela, Erwin, 2017-12-15 08:00

结果 PatientList table 应按 LastVisit DESC:

排序
ID001, Doe, John, William, 2018-06-28 12:45
ID003, Andersen, Pamela, Erwin, 2018-06-20 20:00
ID002, Parson, Rob, Michael, 2018-05-30 11:00

任何帮助将不胜感激。

谢谢

WITH
    a AS (
        SELECT ID, Last, First, Middle, Date FROM Holter
        UNION
        SELECT ID, Last, First, Middle, Date FROM ABP
        UNION
        SELECT ID, Last, First, Middle, Date FROM Resting
    ) ,
    b AS (
        SELECT ID, Last, First, Middle, Date,
               ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) AS RowNumber
        FROM   a
    )
INSERT  Patient
SELECT  ID, Last, First, Middle, Date
FROM    b
WHERE   RowNumber = 1;