簡體   English   中英

嘗試在同一個表中包含具有完全外連接和比較的行

[英]Trying to include rows with a Full Outer Join & Comparing in the same table

I'm attempting to return the First person to check in in each Room_id by joining the PERSON and CHECK_IN tables http://sqlfiddle.com/#!17/35d930 > Select PostGreSQL 9.6 > Build Schema > Paste Query

CREATE TABLE person
    ("id" int)
;
    
INSERT INTO person
    ("id")
VALUES
    (1),
    (2),
    (3),
    (4),
    (5),
    (6)
;

CREATE TABLE check_in
    ("id" int, "person_id" int, "room_id" int, "check_in_date" timestamp, "check_out_date" timestamp)
;
    
INSERT INTO check_in
    ("id", "person_id", "room_id", "check_in_date", "check_out_date")
VALUES
    (100, 1, 202, '2020-10-01 00:00:00', '2021-09-05 00:00:00'),
    (101, 2, 201, '2020-12-15 00:00:00', '2021-02-15 00:00:00'),
    (104, 3, 204, '2021-05-20 00:00:00', '2021-07-04 00:00:00'),
    (106, 4, 202, '2022-08-01 00:00:00', NULL),
    (108, 3, 204, '2021-08-15 00:00:00', NULL)
;


select c1.person_id, c1.room_id, c1.check_in_date
from check_in c1
FULL OUTER JOIN check_in c2 on c2.room_id = c1.room_id
where c1.check_in_date < c2.check_in_date 
order by c1.room_id

我要返回 room_ids 202 和 204,但無法讓 select 返回 201 .. 我不應該使用完整的外連接嗎?

我們不需要加入person表,因為我們在check_in表中擁有我們需要的所有信息。

select   id 
        ,person_id  
        ,room_id    
        ,check_in_date  
        ,check_out_date
from    (
         select   *
                  ,row_number() over(partition by room_id order by check_in_date desc) as rn
         from     check_in
        ) t
where   rn = 1
ID person_id room_id 登記日期 離開日期
101 2 201 2020-12-15 00:00:00 2021-02-15 00:00:00
106 4 202 2022-08-01 00:00:00 null
108 3 204 2021-08-15 00:00:00 null

小提琴

您的 where 條件將外部聯接轉換為內部聯接。 請參閱上面的 window function 的答案

select c1.person_id, c1.room_id, c1.check_in_date
from check_in c1
where c1.check_in_date = (select min(c2.check_in_date) from check_in c2 
  where c2.room_id = c1.room_id ) 
order by c1.room_id

select c1.person_id, c1.room_id, c1.check_in_date from check_in as c1 where c1.check_in_date in (select min(check_in_date) from check_in as c2 join person as p on p.id = c2.person_id group by c2.room_id) group by 2,1,3 order by c1.room_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM