根据不同条件汇总列?

时间:2019-09-13 02:55:09

标签: sql group-by teradata aggregate-functions query-performance

我有一个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

1 个答案:

答案 0 :(得分:1)

给出您的规则,可能需要两个步骤-首先进行重复数据删除,然后进行汇总:

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;