我想要实现的目标:
数据库是postgres。我们为用户订购了购买日期和user_id
。我想得到订购此期间和上一期的用户数(比如说它是一周,然后是本周和上周订购的人)。
我是SQL的新手,能够获得本周的用户数,但这就是它停止的地方。
SELECT
COUNT(distinct(user_id))
FROM
orders
WHERE
shipment_state = 'shipped' AND
delivery_date >= '2017-11-01' AND
delivery_date <= '2017-11-10'
我现在该如何制作,以便获得那段时间内订购的人数,以及11月1日前一周的f.ex?
答案 0 :(得分:0)
这是一个有点蛮力,但假设“这个时期”意味着十一月,“最后一个时期”意味着十月,这将是一种方式:
with cte as (
SELECT
user_id,
sum (case when delivery_date
between '2017-10-01' and '2017-10-31' then 1 else 0 end) as last,
sum (case when delivery_date
between '2017-11-01' and '2017-11-30' then 1 else 0 end) as this
FROM
orders
where
shipment_state = 'shipped' and
delivery_date >= '2017-10-01'
group by user_id
)
select count (*)
from cte
where last > 0 and this > 0
如果没有对值进行硬编码,你可以做几周的一种方法是做这样的事情:
delivery_date between date_trunc ('week', current_date) and
date_trunc ('week', current_date) + interval '6 days'
对于本周以及之前一周的回升一周:
delivery_date between date_trunc ('week', current_date) - interval '1 week' and
date_trunc ('week', current_date) - interval '1 day'
答案 1 :(得分:0)
我会这样做:
SELECT COUNT(DISTINCT CASE WHEN delivery_date >= '2017-11-01' AND delivery_date <= '2017-11-10'
THEN user_id
END),
COUNT(DISTINCT CASE WHEN delivery_date >= '2017-11-01' - INTERVAL '1 week' AND delivery_date < '2017-11-01'
THEN user_id
END)
FROM orders o
WHERE shipment_state = 'shipped' AND
delivery_date >= '2017-11-01' - INTERVAL '1 week' AND
delivery_date <= '2017-11-10';
答案 2 :(得分:0)
SELECT COUNT(DISTINCT CASE WHEN delivery_date >= '2017-11-01'
AND delivery_date <= '2017-11-10'
THEN user_id
END)
FROM orders o
WHERE user_id = (SELECT DISTINCT user_id
FROM orders o
WHERE
shipment_state = 'shipped' AND
delivery_date >= '2017-11-30' - INTERVAL '1 week' AND
delivery_date <= '2017-11-01')
AND
shipment_state = 'shipped' AND
delivery_date >= '2017-11-01' - INTERVAL '1 week' AND
delivery_date <= '2017-11-10';