尝试创建显示活动/非活动帐户的CASE字段。活跃帐户在过去90天内下了订单。
我遇到了数据类型的问题,无法找到解决方案。这是我正在尝试运行的代码:
SELECT DISTINCT ON (accountid)
accountid, customer, round(AVG(qty),2) AS average_order_qty, ROUND(AVG(total),2) AS avg_order_rev, (CURRENT_DATE - MAX(date)) as days_since_order, (CURRENT_DATE - MAX(date)) as active,
CASE
WHEN (CURRENT_DATE - MAX(date)) <= CURRENT_DATE - 90 THEN 'Yes'
ELSE 'No'
END
FROM m2m_kit_total
GROUP BY accountid, customer
ORDER BY accountid, MAX(date) DESC NULLS LAST;
这是我得到的错误代码:
ERROR: operator does not exist: interval <= date
LINE 4: WHEN (CURRENT_DATE - MAX(date)) <= CURRENT_DATE - 90 THEN...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
SQL state: 42883
Character: 261
非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
请尝试在下面运行:
SELECT DISTINCT ON (accountid)
accountid, customer, round(AVG(qty),2) AS average_order_qty, ROUND(AVG(total),2) AS avg_order_rev, (CURRENT_DATE - MAX(date)) as days_since_order, (CURRENT_DATE - MAX(date)) as active,
CASE
WHEN ((CURRENT_DATE - MAX(date)) = (CURRENT_DATE - 90)) THEN 'Yes'
ELSE 'No'
END
FROM m2m_kit_total
GROUP BY accountid, customer
ORDER BY accountid, MAX(date) DESC NULLS LAST;
答案 1 :(得分:0)
我相信这是你想要的逻辑:
SELECT accountid, customer, round(AVG(qty), 2) AS average_order_qty,
ROUND(AVG(total), 2) AS avg_order_rev,
(CURRENT_DATE - MAX(date)) as days_since_order,
(CASE WHEN MAX(date) >= CURRENT_DATE - INTERVAL '90 DAY' THEN 'Yes'
ELSE 'No'
END) as is_active
FROM m2m_kit_total
GROUP BY accountid, customer
ORDER BY accountid, MAX(date) DESC NULLS LAST;
这是两个日期的简单比较。它应该没有任何问题。
我也猜测每个帐户只有一个客户,因此每accountid
返回一行,而不依赖distinct on
。