2015-10-30 72 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)

相關問題