-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 –