【问题标题】:Add the last appearance to table将最后一个外观添加到表中
【发布时间】:2021-04-28 12:24:13
【问题描述】:

我有两张桌子(例如)
table1 将包含商店,有 2 种类型“糖果店”和“牙科店”。 每行包含有关客户在特定商店购买的信息

table1(购买):

+----+---------+------------------+-------+
| id | store   | date of purchase | money |
| 1  | store 1 | 2016-01-01       | 10    |
| 1  | store 5 | 2018-01-01       | 50    |
| 2  | store 2 | 2017-01-20       | 10    |
| 2  | store 3 | 2019-02-20       | 15    |
| 3  | store 2 | 2017-02-02       | 20    |
| 3  | store 6 | 2019-01-01       | 60    |
| 1  | store 1 | 2015-01-01       | 20    |
+----+---------+------------------+-------+

table2(类型):

+---------+--------+
| store   | type   |
| store 1 | candy  |
| store 2 | candy  |
| store 3 | candy  |
| store 4 | dental |
| store 5 | dental |
| store 6 | dental |
+---------+--------+

我希望我的查询返回这样的表:

+----+---------------+-----------------+---------------+
| id | the last place| the last date c |the last date d|
| 1  | store 5       | 2016-01-01      |  2018-01-01   |
| 2  | store 3       | 2019-02-20      |  -            |
| 3  | store 6       | 2017-02-02      |  2019-01-01   |
+----+---------------+-----------------+---------------+

在哪里

  • [最后一个地方]是客户最后购买的店铺;

  • [最后日期 c] - 在糖果店购买的最后日期

  • [最后日期d]是最后在牙科店购买的日期

如果没有任何匹配项,则删除行(所有值均为空)

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    你可以使用条件聚合和join:

    select t1.id,
           (array_agg(store order by t1.date_of_purchase desc))[1] as last_store,
           max(t1.date_of_purchase) filter (where t2.type = 'candy') as last_candy,
           max(t1.date_of_purchase) filter (where t2.type = 'dental') as last_dental
    from table1 t1 join
         table2 t2
         using (store)
    group by t1.id;
    

    【讨论】:

    • 如何通过购买返回最后一个店铺?
    • @Qugean 。 . .哎呀,我错过了。我更新了答案。
    • @Qugean 。 . .我修正了错字。它返回的是第一家商店,而不是最后一家。
    【解决方案2】:

    你可以在 postgresql 中使用 group by,maxwindow function :

    select id
    ,max(case when rnb=1 then store else null end) the_last_place
    ,max(case when type='candy' then date else null end) the_last_date_c
    ,max(case when type='dental' then date else null end) the_last_date_d
     from(
        select t1.id,t1.store,t1.date,row_number() over(partition by t1.id order by t1.date desc) rnb
        from table1 t1 
        inner join table2 t2 
        on t1.store=t2.store
        ) t
    group by id ;
    

    【讨论】:

    • 您的请求返回正确的商店但不是日期(日期为空)
    • 也是很好的解决方案,但是你错过了字段 "type" ,它应该像 max(case when type='candy' then date else null end) the_last_date_c ,max(case when type='dental'然后 date else null end) the_last_date_d 和 in from (select....., type, ....)
    • o,'type' 替换 'store' 是错误的,我已经更正了。
    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    相关资源
    最近更新 更多