这是一个比我通常遇到的报告问题稍微复杂一些的问题,我想知道客户已经回购了多少次单个产品列表(比如说,有些产品的销售量很高,但我们想知道有多少是首次购买的,有多少是回购的)。
items_purchased:
+----------+------------+----------+
| buyer_id | listing_id | quantity |
+----------+------------+----------+
| 1234 | 5678 | 1 |
| 1234 | 3456 | 1 |
| 9012 | 3456 | 2 |
| 7901 | 5678 | 1 |
| 1234 | 5678 | 1 |
+----------+------------+----------+
字符串
从这些数据,我可以看到上市5678
已购买3次,但回购一次.上市3456
已购买两次,但从未回购.我想建立一个报告如下:
+------------+-----------+-------------+-----------------+
| listing_id | purchases | repurchases | repurchase_rate |
+------------+-----------+-------------+-----------------+
| 5678 | 1364 | 152 | 11% |
| 3456 | 892 | 289 | 32% |
| 3284 | 51 | 30 | 59% |
| 8763 | 8 | 0 | 0% |
+------------+-----------+-------------+-----------------+
型
我想我需要一个DISTINCT
或GROUP BY
的地方,肯定是一个SUM
我猜,但我难住了如何做到这一点。
4条答案
按热度按时间mkh04yzy1#
您可以:
字符串
测试结果:
型
请参见db<>fiddle上的运行示例。
bprjcwpo2#
在我的脑海中,你可以构建一个CTE,将特定
listing_id
的购买计数汇总为buyer_id
,每个减去1以包括 * 仅 * 回购:字符串
DB Fiddle
考虑到子查询的无偿使用,这可能不是计算效率最高的方法,但我相信还有进一步优化的空间来适应规模化的使用。
ego6inou3#
使用
count()
和count() - count(distinct)
分别计算购买和回购。字符串
| listing_id|购买|回购|回购利率|
| --|--|--|--|
| 3456 | 2 | 0 |0%的百分比|
| 5678 | 3 | 1 |百分之三十三|
db fiddle
jc3wubiy4#
字符串
此查询执行以下操作:
first_purchases
标识每个buyer_id
和listing_id
的第一次购买items_purchased
表两次:一次是计算所有购买(p
),一次是计算回购(r
)repurchases
计数经过筛选,仅包括quantity
数量大于first_purchase
数量的采购repurchase_rate
并格式化输出需要注意的是,上面的查询假设回购是指后续的采购数量大于第一次采购数量,请根据您具体的回购定义调整逻辑。