同时使用RANK与COUNT(DISTINCT)聚合

时间:2016-04-04 08:59:46

标签: sql sql-server postgresql

我有一个子查询,它连接我的客户和交易表,别名为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中执行此操作?

1 个答案:

答案 0 :(得分:1)

Microsoft SQL Server

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