我在 postgres 中有 2 個表。
用戶
| auth0_id | 電子郵件 |
|---|---|
| 123-A | 一個@a |
| 123-B | 乙@乙 |
| 123-C | c@c |
auth0_logs
| ID | 日期 | 用戶身份 | 客戶名稱 |
|---|---|---|---|
| abc-1 | 021-10-16T00:18:41.381Z | 123-A | example_client |
| abc-2 | ... | 123-A | example_client |
| abc-3 | ... | 123-B | example_client |
| abc-4 | ... | 123-A | example_client |
| abc-5 | ... | 123-B | example_client |
| abc-6 | ... | 123-C | example_client |
我正在嘗試獲取加入 user.auth0_id 上的用戶表的每個唯一用戶 (auth0_logs.user_id) 的最后登錄資訊(基于 MAX(auth0_logs.date) 的 auth0_logs 表中的單行)。
[
{
// auth0_logs information
user_id: "123-A",
last_login: "021-10-16T00:18:41.381Z",
client_name: "example_client",
// users information
email: "a@a"
},
{
user_id: "123-B",
last_login: "...",
client_name: "example_client",
email: "b@b"
},
{
user_id: "123-C",
last_login: "...",
client_name: "example_client",
email: "c@c"
}
]
我知道這是一個問題,在使用聚合器的查詢中不允許使用“裸”列(未添加到 GROUP BY - 但添加到 GROUP BY 回傳 > 1 行),但我無法獲得適用于其他的解決方案SO 帖子(我發現的最佳帖子:SQL 僅選擇列上具有最大值的行)。我向你保證,在過去的幾天里,我已經在這上面做了很多小時......
-- 編輯:開始 --
I have removed my incorrect attempts as to not confuse / misdirect future readers. Please see @MichaelRobellard answer using the WITH clause based on the above information.
-- EDIT: end --
Any help or further research direction would be greatly appreciated!
uj5u.com熱心網友回復:
with user_data as (
select user_id, max(date) from auth0_logs group by user_id
)
select * from user_data
join auth0_logs on user_data.user_id = auth0_logs.user_id
and user_data.date = auth0_logs.date
join users on user_data.user_id = users.auth0_id
uj5u.com熱心網友回復:
with
t as
(
select distinct on (user_id) *
from login_logs
order by user_id, ldate desc
),
tt as
(
select auth0_id user_id, ldate last_login, client_name, email
from t join users on auth0_id = user_id
)
select json_agg(to_json(tt.*)) from tt;
SQL在這里擺弄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/321566.html
標籤:sql postgresql join group-by aggregate-functions
