[英]Need some help in joining two tables
I have two tables status and admit table as follows: 我有两个表状态和接纳表,如下所示:
Admit 承认
cono|resno|date |admit_disch
---------------------------------
05 |108 |2018-11-28|R
05 |108 |2018-11-17|D
05 |108 |2016-03-07|A
Status 状态
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
I would like to join these tables to give me output as below: 我想加入这些表,以得到如下输出:
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
If you are looking for the result as for the non matched entry in the Admit
table, you are required A
as admit_disch, then the following will work. 如果你正在寻找的结果是在非匹配条目
Admit
表,您需要A
为admit_disch,那么下面的工作。
Seeing your output the matched entry in the top ordering then the order by date, so I added a column ManualOrder
to fix this issue: 看到您的输出匹配的条目是按最高顺序排列的,然后是按日期排序,因此我添加了
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
尝试使用内部联接查询
Select admit.cono, admit.resno, admit.date, admit.admit_disch, Status.in_out from admit Inner join Status ON admit.cono=Status=cono
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.