我正在尝试总结 Amazon Redshift 上按新字段分组的 Name 和 id 的总体利润和交易结果。数据示例如下: 表格数据示例 执行后,我想根据以黄色突出显示的三个字段显示每个人的数据。
示例代码示例:
*Select Id, Name,
sum (CASE when date = '9/1/2024' then profit) as profit_CYR,
sum (CASE when date = '12/1/2023' then profit) as profit_last_year,
sum (CASE when date = '9/1/2023' then profit) as profit_last_year_to_date
from table*
我只是不想使用硬编码的日期。
嗨,我认为您可以使用日期函数根据当前日期确定这些值。
SELECT
id, name,
SUM(CASE WHEN date = (SELECT MAX(date) FROM table WHERE date <= current_date) THEN profit ELSE 0 END) AS profit_CYR,
SUM(CASE WHEN date = date_trunc('month', current_date - interval '1 year') THEN profit ELSE 0 END) AS profit_last_year,
SUM(CASE WHEN date = current_date - interval '1 year' THEN profit ELSE 0 END) AS profit_last_year_to_date
FROM table GROUP BY id,name;