2015-10-30 59 views
-1

我想从订单起始日起7天内获得客户的订单数量和金额。我设法用一个公共表格表达式来做到这一点,但很好奇,看看是否有人可以指出对主要查询的WHERE或HAVING部分或子查询的明显更新。Postgresql - 您可以在没有CTE的情况下执行此操作吗?

--This is a temp table to use in the main query 
WITH first_seven AS 

    (
    select min(o.created_at), min(o.created_at) + INTERVAL '7 day' as max_order_date, o.user_id 
    from orders o 
    where o.total_price > 0 and o.status = 30 
    group by o.user_id 
    having min(o.created_at) > '2015-09-01' 
    ) 


--This is the main query, find orders in first 7 days of purchasing 

SELECT sum(o.total_price) as sales, count(distinct o.objectid) as orders, o.user_id, min(o.created_at) as first_order 
from orders o, first_seven f7 
where o.user_id = f7.user_id and o.created_at < f7.max_order_date and o.total_price > 0 and o.status = 30 
group by o.user_id 
having min(o.created_at) > '2015-09-01' 
+1

如果您不提供至少您的表DDL,某些数据示例,预期结果和您的PostgreSQL版本,没有人可以帮助您。 – Houari

+1

如果你喜欢,你可以把它变成一个子查询。顺便说一句,从不在'from'子句中使用逗号。始终使用明确的“join”语法。 –

+0

这只是一个标准的交易表,orderid,customerid,orderdate和totalprice –

回答

0

您可以使用窗口函数做到这一点,而不join

select sum(o.total_price) as sales, count(distinct o.objectid) as orders, 
     o.user_id, min(o.created_at) as first_order 
from (select o.*, 
      min(o.created_at) over (partition by user_id) as startdate 
     from orders o 
     where o.total_price > 0 and o.status = 30 
    ) o 
where startdate > '2015-09-01' and 
     created_at <= startdate + INTERVAL '7 day'; 

一个更复杂的查询(用正确的索引)可能是更有效的:

select sum(o.total_price) as sales, count(distinct o.objectid) as orders, 
     o.user_id, min(o.created_at) as first_order 
from (select o.*, 
      min(o.created_at) over (partition by user_id) as startdate 
     from orders o 
     where o.total_price > 0 and o.status = 30 and 
      not exists (select 1 from orders o2 where o2.user_id = o.user_id and created_at <= '2015-09-01') 
    ) o 
where startdate > '2015-09-01' and 
     created_at <= startdate + INTERVAL '7 day'; 

该过滤器在Windows计算之前淘汰老客户,这应该会提高效率。有用的索引是orders(user_id, created_at)orders(status, total_price)

相关问题