【问题标题】:How to join 2 tables on the same id but different date ranges?如何在相同的 id 但不同的日期范围内加入 2 个表?
【发布时间】:2019-08-15 02:49:25
【问题描述】:

我正在使用 Presto SQL 并尝试计算每个按国家和客户状态细分的网站每天登录的客户数量?从“新”到“退货”需要 2 天时间。结果应如下所示:

date        country     status  total_count
2019-08-01  usa         new      1
                        return   null
            canada      new      1
                        return   1
table a : country of customers
login_date      id      country
2019-08-01      1       usa
2019-08-01      4       canada
2019-08-01      5       canada
2019-08-02      1       usa
2019-08-02      3       usa
2019-08-02      4       usa
2019-08-03      1       usa
2019-08-03      2       canada
2019-08-03      3       usa
2019-08-03      4       usa
2019-08-03      5       canada

table b : daily status of customers. 
**It takes 2 days to update the status from ‘new’ to ‘return’  
purchase_date       id      customer_status
2019-08-01      5           return
2019-08-02      4           new
2019-08-02      5           return
2019-08-03      1           return
2019-08-03      2           new
2019-08-03      3           return
2019-08-04      4           return

关于如何连接 2 个不同日期的表有什么建议吗?我认为该表应在同一日期加入,并延迟 2 天。

SELECT a.date,
a.country,
b.customer_status,
COUNT(id)
FROM table_a a
LEFT JOIN table_b b
ON (a.id = b.id AND ‘how should I join on date that’s 2 days delay?’)
GROUP BY 1,2

非常感谢!!

【问题讨论】:

  • 嗨,我正在使用 Presto SQL

标签: sql presto


【解决方案1】:

你需要这个,DATE_ADD(date, INTERVAL 2 DAY)

SELECT a.date,
a.country,
b.customer_status,
COUNT(id)
FROM table_a a
LEFT JOIN table_b b
ON (a.id = b.id AND a.login_date = DATE_ADD(b.purchase_date, INTERVAL 2 DAY))
GROUP BY 1,2

【讨论】:

  • date_add 是非标准 SQL。请说明适用于哪个 DBMS 产品。
  • 感谢 Mohideen!但它仍然不起作用。我也在使用 presto sql 并且已经尝试过这个:SELECT a.date, a.country, b.customer_status, COUNT(id) FROM table_a a LEFT JOIN table_b b ON (a.id = b.id AND a.login_date = DATE_ADD(DAY, 2, b.purchase_date)) GROUP BY 1,2 prestodb.github.io/docs/current/functions/datetime.html
  • @mohideen-bin-mohammed @january28 DATE_ADD 函数的语法有点错误。应该是DATE_ADD('DAY', 2, b.purchase_date)
猜你喜欢
  • 1970-01-01
  • 2019-06-13
  • 2021-04-29
  • 2023-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
相关资源
最近更新 更多