我有一个具有以下结构的商店数据库:
s_articles: all products
id | name | mode
s_order: all orders
id | ordertime | userId | status
s_order_details: all line items for an order
id | orderId | articleId
现在我希望实现以下目标:我想现在有多少用户在过去90天内购买了产品,并且在过去90天之前购买了相同的产品。
我是这样做的:我收到所有文章,然后我会计算在过去90天"boughtBefore90"
之前购买过该文章的所有客户,然后我有另一个子选择与另一个子选择我在哪里收集过去90天内购买该产品的所有用户,并在此之前购买该产品并将其保存在"boughtLast90"
。
然后我计算保留率。这适用于一种产品,但不适用于整篇文章数据库。有没有办法编写这个具有更好性能的SQL?
我的查询如下:
select articleId, articleName, boughtBefore90, boughtLast90, boughtLast90/boughtBefore90 as 'retention'
FROM
(select
s_articles.id as 'articleId',
s_articles.name as 'articleName',
(select count(*)
FROM s_order_details as s_order_details_2
join s_order as s_order_2 on s_order_2.Id = s_order_details_2.orderId
where s_order_details_2.articleId = s_articles.id
and (s_order_2.status = 0 or s_order_2.status = 2)
and s_order_2.ordertime > '2017-01-01 00:00:00'
and s_order_2.ordertime < '2017-03-09 23:59:59'
) as 'boughtBefore90',
(select count(*) from s_order_details as s_order_details_3
join s_order as s_order_3 on s_order_3.id = s_order_details_3.orderId
where s_order_3.ordertime > '2017-03-10 00:00:00'
and s_order_3.ordertime < '2017-06-07 23:59:59'
and s_order_details_3.articleId = s_articles.id
and (s_order_3.status = 0 or s_order_3.status = 2)
AND s_order_3.userId = (
select DISTINCT(s_order_4.userId) from s_order_details as s_order_details_4
join s_order as s_order_4 on s_order_4.id = s_order_details_4.orderId
where s_order_4.ordertime > '2017-01-01 00:00:00'
and s_order_4.ordertime < '2017-03-09 23:59:59'
and s_order_details_4.articleId = s_articles.id
and s_order_3.userId = s_order_4.userId
and (s_order_4.status = 0 or s_order_4.status = 2))
) as 'boughtLast90'
from
s_articles
join s_order_details on s_order_details.articleID = s_articles.id
join s_order on s_order.id = s_order_details.orderId
WHERE s_articles.mode = 0
AND s_order_details.modus = 0
AND (s_order.status = 2 or s_order.status = 0)
group by s_articles.id) as resulttable;
谢谢!
答案 0 :(得分:0)
这似乎是一个非常简单的查询。以下是客户和文章列表:
select o.customerid, od.articleid
from s_orders o join
s_order_details od
on od.orderid = o.id
group by o.customerid, od.articleid
having max(o.ordertime) > curdate() - interval 90 days and
min(o.ordertime) <= curdate() - interval 90 days;
如果您想要计数,请将其用作子查询,并使用count(*)
(对于客户/文章对)或count(distinct customerid)
(对于客户数量)。