sql - 统计30天内购买过不同产品的用户

标签 sql postgresql

 user_id    product_type  reservation_date   used_date
|12345     |     A       |   2016-06-01    | 2016-06-24 |
|12345     |     B       |   2016-06-03    | 2016-06-24 |
|12345     |     C       |   2016-07-02    | 2016-07-30 |
|12346     |     A       |   2016-06-27    | 2016-07-24 |
|12346     |     B       |   2016-06-29    | 2016-07-22 |

我想弄清楚我们平台上的“交叉销售”效果。 在上表中,user_id 12345 购买了product_type A, BC 一个月(和一天)内。

我想计算在 reservation_date 的 30 天间隔内购买了任何类型产品但至少购买了 2 种不同类型产品的用户数量。

有什么办法吗?我写了一个如下所示的查询,但我认为这是不准确的,因为我无法计算具有我希望看到的输出的正确条件的日期。

SELECT
DATE_TRUNC('month', reservation.date),
COUNT(DISTINCT(user.id)),
FROM reservation
INNER JOIN products ON products.id = reservation.product_id
INNER JOIN users ON users.id = reservation.user_id
WHERE products.type = 'A'
AND user.id IN(
SELECT user.id
FROM reservation
INNER JOIN products ON products.id = reservation.product_id
INNER JOIN users ON users.id = reservation.user_id
WHERE product.type in ('B','C')
GROUP BY 1,2 ORDER BY 1 DESC;

最佳答案

可能像这样的东西会起作用

SELECT COUNT(DISTINCT(r.user_id))
  FROM reservation r
 INNER JOIN reservation r_a
         ON r_a.user_id = r.user_id
        AND r_a.product_type <> r.product_type
        AND @extract(day FROM (r_a.reservation_date::TIMESTAMP - r.reservation_date::TIMESTAMP)) <= 30

@extract(timepart from (one_timestamp - another_timestamp) 将等于“timeparts”的绝对值在两个时间戳之间的差值

关于sql - 统计30天内购买过不同产品的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37381951/

相关文章:

mysql - 在 MySQL 中返回不为 null 的结果

mysql - 将三个 mysql 表中的员工值相加

php - 如何通过在 php 中使用 javascript 选择从 SQL 填充的下拉列表来将 SQL 中的值检索到文本区域中

c# - MVC4 使用 linq to sql 返回存储过程输出

postgresql - OpenERP - 访问 Odoo 应用程序时重定向到 "Create a New Database"页面

postgresql - 如何使用 Tableau 桌面软件连接到 AWS RedShift?

postgresql - Postgres 外部编辑器不在 savequit 上执行查询

mysql - 降级AWS RDS实例

mysql - 使用多个连接优化查询

java - 将通用 java 类型保存/加载到 postgresql 数据库列