根据不同条件聚合列?

Aggregate columns based on different conditions?

我有一个 Teradata 查询生成:

customer | order | amount | days_ago
123      | 1     | 50     | 2
123      | 1     | 50     | 7
123      | 2     | 10     | 19
123      | 3     | 100    | 35
234      | 4     | 20     | 20
234      | 5     | 10     | 10

考虑到性能,什么是为每个客户生成输出的最有效方法,其中 orders 是客户在过去 30 天内的不同订单数量,total 是总和无论多少天前下订单,不同订单的金额是多少?

期望的输出:

customer | orders | total
123      | 2      | 160
234      | 2      | 30

根据您的规则,可能需要两个步骤 - 先去重,然后聚合:

SELECT customer, 
SUM(CASE WHEN days_ago <=30 THEN 1 ELSE 0 END) AS orders,
SUM(amount) AS total
 FROM
(SELECT customer, order, MAX-or-MIN(amount) AS amount, MIN-or-MAX(days_ago) AS days_ago
FROM your_relation
GROUP BY 1, 2) AS DistinctCustOrder
GROUP BY 1;