我有一个子查询,它连接我的客户和交易表,别名为jq
。我想按订单时间戳(order_ts
)创建每个客户的购买(交易)排名。所以我做到了,
SELECT customer_id,
order_id,
order_ts,
RANK() OVER (PARTITION BY customer_id ORDER BY order_ts ASC) AS purchase_rank,
amount
FROM jq GROUP BY customer_id
ORDER BY customer_id;
除purchase_rank
列外,我还想了解客户已完成的总购买量。所以这就变成了:
SELECT customer_id,
order_id,
order_ts,
RANK() OVER (PARTITION BY customer_id ORDER BY order_ts ASC) AS purchase_rank,
// total purchases of this customer, counted by order_id
amount
FROM jq GROUP BY customer_id
ORDER BY customer_id;
有些order_id
是重复的,所以我想明确计算。如何在不加入子查询的情况下在MS SQL Server和Postgres中执行此操作?
答案 0 :(得分:1)
SELECT customer_id,
order_id,
order_ts,
purchase_rank,
MAX(cnt) OVER(PARTITION BY customer_id) AS purchase_cnt,
amount
FROM
(
SELECT customer_id,
order_id,
order_ts,
RANK() OVER (PARTITION BY customer_id ORDER BY order_ts ASC) AS purchase_rank,
DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY order_id ASC) AS cnt,
amount
FROM jq
-- GROUP BY customer_id
) AS D
ORDER BY customer_id;
抱歉,我不熟悉postgresql
。