简体   繁体   English

Select 最后订单日期,postgreSQL 中特定卖家的所有订单 ID 和用户 ID

[英]Select last order date, all the order id and user id for particular seller in postgreSQL

I am new to postgreSQL我是 postgreSQL 的新手

Updated Initial Question:更新的初始问题:

I have two tables orders & users我有两个表ordersusers

user_id用户身份 username用户名
a一个 user1用户1
b b user2用户2
c c user3用户3
order_id order_id ordered_at有序的_at user_id用户身份 seller_id卖家id
1 1 2022-08-10 2022-08-10 a一个 s1 s1
2 2 2022-08-09 2022-08-09 b b s1 s1
3 3 2022-07-06 2022-07-06 a一个 s2 s2
4 4 2022-08-01 2022-08-01 a一个 s1 s1
5 5 2022-05-02 2022-05-02 c c s1 s1
6 6 2022-08-11 2022-08-11 b b s2 s2
7 7 2022-08-12 2022-08-12 b b s1 s1

My postgres SQL query should give me the result for seller s1:我的 postgres SQL 查询应该给我卖家 s1 的结果:

order_id order_id last_purchase最后一次购买 user_id用户身份 username用户名
1 1 2022-08-10 2022-08-10 a一个 user1用户1
4 4 2022-08-10 2022-08-10 a一个 user1用户1
2 2 2022-08-12 2022-08-12 b b user2用户2
7 7 2022-08-12 2022-08-12 b b user2用户2
5 5 2022-05-02 2022-05-02 c c user3用户3

For this I have wrote the SQL query:为此,我编写了 SQL 查询:

        SELECT
            MAX(orders.ordered_at) AS last_purchase,
            orders.order_id AS order_id,
            users.user_id AS users_id,
            users.username as username
        FROM
            orders
        INNER JOIN
            users
        ON
            orders.user_id = users.user_id
        WHERE 
            orders.seller_id='s1'
        GROUP BY users.user_id;

I am not getting the desired output我没有得到想要的 output

Any suggestions or help is welcomed.欢迎任何建议或帮助。 Thank you!谢谢!

if I am understanding your question you want last purchase to be the max date per user id.如果我理解您的问题,您希望最后一次购买是每个用户 ID 的最大日期。 if so use a windowing function如果是这样,请使用窗口 function

 SELECT
            MAX(orders.ordered_at) over
             (partition by users.users_id  order by orders.ordered_at desc) as 
             last_purchase,
            orders.order_id AS order_id,
            users.users_id AS users_id,
            users.username as username
        FROM
            orders
        INNER JOIN
            users
        ON
            orders.user_id = users.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM