我有问题分组用户在'Group_3'在2连续年.想法是组用户在第3组下订单是超过2000年收入在2连续年.
SELECT email_id,
COUNT(*) as num_of_orders,
SUM(revenue) AS total_money_spent,
CASE WHEN
SUM(CASE WHEN order_creation_date BETWEEN '2016-01-01' and '2016-12- 31'
THEN revenue END) > 2000
THEN 'Group_1'
WHEN
SUM(CASE WHEN order_creation_date BETWEEN '2015-01-01' and '2016-12-31'
THEN revenue END) > 2000
THEN 'Group_2'
WHEN
SUM(CASE WHEN EXTRACT(years FROM order_creation_date) <> LAG(EXTRACT(years FROM order_creation_date))
OVER(PARTITION BY email_id ORDER BY EXTRACT(years FROM order_creation_date)) + 1
THEN revenue END) > 2000
THEN 'Group_3'
WHEN
SUM(CASE WHEN order_creation_date BETWEEN '2015-01-01' and '2016-12-31'
THEN revenue END) < 2000
THEN 'Group_4'
WHEN
SUM(CASE WHEN order_creation_date BETWEEN '2015-01-01' and '2016-12-31'
THEN revenue END) = 0
THEN 'Group_5'
END
FROM sql_test
GROUP BY email_id
ORDER BY num_of_orders DESC;
我得到:
聚合函数调用不能包含窗口函数调用
第13行:...E WHEN EXTRACT(years FROM order_creation_date)〈〉LAG(EXTRAC..
我猜我不能在CASE
查询中使用LAG
?
1条答案
按热度按时间4ioopgfo1#
窗口函数在
SELECT
语句中 * 在 * 聚合函数之后执行。你不能以相反的顺序嵌套它们。考虑事件的顺序:请改用子查询:
当你在它:聚合
FILTER
表达式比那些CASE
表达式更优雅和更快。请参阅: