我試圖將三個表與父表連接起來,以獲取客戶 id、訪問 id和訪問日期的輸出,如果有多個日期,則選擇最早的日期。所有四個表都包含 cust_id、visit_id 和visit_date 變數,但visit_id 是鏈接變數。我將四個表命名為 a、b、c 和 d,以簡化下面的代碼(a 是父表)。
下面我當前的代碼使我更接近我想要的輸出,但我不確定如何通過visit_id獲得一個包含最舊日期的visit_date列,并且不確定如何洗掉重復項。任何幫助將不勝感激,如果我能澄清任何事情,請告訴我!
SELECT
a.cust_id,
a.visit_id,
a.visit_date,
b.visit_date,
c.visit_date,
d.visit_date
FROM a
LEFT JOIN b
ON a.visit_id = b.visit_id
LEFT JOIN c
ON a.visit_id = c.visit_id
LEFT JOIN d
ON a.visit_id = d.visit_id
WHERE a.visit_date IS NOT NULL
OR b.visit_date IS NOT NULL
OR c.visit_date IS NOT NULL
OR d.visit_date IS NOT NULL;
我當前的輸出如下所示:
| cust_id | 訪問 ID | 訪問日期 | 訪問日期 | 訪問日期 | 訪問日期 |
|---|---|---|---|---|---|
| 001 | 001 | 2013-05-23 | |||
| 002 | 002 | 2013-06-03 | 2013-05-27 | ||
| 003 | 003 | 2013-06-05 | 2013-06-05 | 2013-06-05 | |
| 003 | 004 | 2013-07-09 | 2013-07-09 | 2013-07-06 |
我想要的輸出如下所示:
| cust_id | 訪問 ID | 訪問日期 |
|---|---|---|
| 001 | 001 | 2013-05-23 |
| 002 | 002 | 2013-05-27 |
| 003 | 003 | 2013-06-05 |
| 003 | 004 | 2013-07-06 |
uj5u.com熱心網友回復:
您可以使用標量LEAST函式:
SELECT
a.cust_id,
a.visit_id,
LEAST(a.visit_date, b.visit_date, c.visit_date, d.visit_date) AS visit_date
FROM a
LEFT JOIN b
ON a.visit_id = b.visit_id
LEFT JOIN c
ON a.visit_id = c.visit_id
LEFT JOIN d
ON a.visit_id = d.visit_id
WHERE
a.visit_date IS NOT NULL OR
b.visit_date IS NOT NULL OR
c.visit_date IS NOT NULL OR
d.visit_date IS NOT NULL;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326857.html
標籤:sql PostgreSQL
上一篇:一個表中的日期在另一個表中的日期之前-Postgres
下一篇:尋找用戶的兩個輸入之間的平均值
