如何从SQL Server中的另一个ID和日期列表中查询匹配ID和日期的数据?

问题描述 投票:1回答:1

我有一张包含患者数据的表格。该表有Patient IDAdmissionDate等。同一患者可能有多个AdmissionDate。我只对选择日期所属的选定患者感兴趣。例如:下表

patient_id | admission_date
-----------+---------------
F001         2018-07-13
F002         2017-04-02
F003         2018-07-13
F004         2018-04-05
F005         2015-06-13
F001         2017-04-02
F002         2018-07-13
F001         2018-04-22

在上表中,F001有3个入场:2018-07-13, 2017-04-02, 2018-04-22F002有2:2017-04-02, 2018-07-13

现在,我在下一栏中有一个ID及其入学日期的电子表格。我分别获取了ID和日期,并将其添加到以下查询中

WITH TableA AS
(
    SELECT 
        CONVERT(date, admission_date) as admit_date, *
    FROM 
        AdmissionTable
    WHERE 
        patient_id IN ('F001', 'F002', 'F003', 'F004', 'F005') 
)
SELECT *
FROM TableA
WHERE admit_date IN ('2018-07-13', '2017-04-02', '2018-07-13','2018-04-05,'2015-06-13','2017-04-02','2018-07-13','2018-04-22')

这将返回我正在寻找的结果,但也超出了我正在寻找的结果。它甚至给出了患者的行,其入院日期也在我正在搜索的日期列表中,而不是电子表格中列出的那些。该查询基本上为我提供了同一患者的多个数据,而不仅仅是我需要的日期行。

我怎样才能解决这个问题?处理它的最佳方法是什么?

期望的结果应如下所示:

patient_id | admission_date
-----------+---------------
F001         2018-04-22
F002         2018-07-13
F003         2018-07-13
F004         2018-04-05
F005         2015-06-13
sql sql-server
1个回答
1
投票

我在想你应该像这样构造查询:

with from_spreadsheet as (
      select v.*
      from (values ('F001', '2018-07-13'), ('F002', '2017-04-02'), . . .
           ) v(patient_id, admission_date)
     )
select a.*
from admissiontable a join
     from_spreadsheet fs
     on fs.patient_id = a.patient_id and
        convert(date, fs.admission_date) = a.admission_date;
© www.soinside.com 2019 - 2024. All rights reserved.