-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'
如果您不提供至少您的表DDL,某些數據示例,預期結果和您的PostgreSQL版本,沒有人可以幫助您。 – Houari
如果你喜歡,你可以把它變成一個子查詢。順便說一句,從不在'from'子句中使用逗號。始終使用明確的「join」語法。 –
這只是一個標準的交易表,orderid,customerid,orderdate和totalprice –