在连接两个表时需要一些帮助

时间:2019-06-26 09:59:29

标签: sql sql-server

我有两个桌子 状态和准入表,如下所示:

承认

cono|resno|date      |admit_disch
---------------------------------
05  |108  |2018-11-28|R 
05  |108  |2018-11-17|D
05  |108  |2016-03-07|A

状态

cono|resno |date      |in_out
-----------------------------
05  |108   |2018-11-28|I
05  |108   |2018-11-17|O
05  |108   |2016-06-05|O
05  |108   |2016-06-05|I
05  |108   |2016-03-18|O
05  |108   |2016-03-18|I
05  |108   |2016-03-07|I

我想加入这些表,以得到如下输出:

cono|date      |resno|admit_disch |in_out
-----------------------------------------
05  |2018-11-28|108  |R           |I
05  |2018-11-17|108  |D           |O
05  |2016-03-07|108  |A           |I
05  |2016-06-05|108  |A           |O
05  |2016-06-05|108  |A           |I
05  |2016-03-18|108  |A           |I   
05  |2016-03-18|108  |A           |I

2 个答案:

答案 0 :(得分:0)

如果您要查找Admit表中不匹配条目的结果,则需要A作为admit_disch,然后将可以使用以下内容。

看到您的输出是按顺序排列的匹配项,然后是按日期排序,因此我添加了列ManualOrder来解决此问题:

SELECT cono, [date], resno, admit_disch, in_out
FROM (
    SELECT S.cono, S.[date], S.resno,
           CASE WHEN A.admit_disch IS NOT NULL THEN 1 ELSE 0 END AS ManualOrder,
           COALESCE(A.admit_disch, 'A') AS admit_disch,
           S.in_out
     FROM [Status] S
     LEFT JOIN Admit A ON A.cono = S.cono 
               AND A.resno = S.resno
               AND A.date = S.date 
) Q
ORDER BY ManualOrder DESC, [date] DESC

Demo on db<>fiddle

答案 1 :(得分:0)

尝试使用内部联接查询

Select admit.cono, admit.resno, admit.date, admit.admit_disch, Status.in_out from admit Inner join Status ON admit.cono=Status=cono