给定一个看起来像这样的表,我将如何创建另一个获取此数据的查询,比较该 store_id 的最早和最晚日期的 sales_net_amt,并返回每个 store_id 一行,显示纯文本是否“增加”或“减少”加班在另一列?
对于计算列,我假设我可以只使用“case when”子句,但我不确定如何导出最新日期和最早日期的两个单独值来进行比较。我能做的最好的事情是创建一个显示最新和最早日期及其sales_net_amt的查询,但我不知道如何将计算列添加到现有值的基础上
这是我所做的查询(QUARTER 列是不需要的,并且使查询不必要地冗长,只是想我会暂时添加它,以防我最终使用它):
select case when extract(month from full_date) between 1 and 3 then substr(item_scan_timestamp, -4) || 'Q1'
when extract(month from full_date) between 4 and 6 then substr(item_scan_timestamp, -4) || 'Q2'
when extract(month from full_date) between 7 and 9 then substr(item_scan_timestamp, -4) || 'Q3'
when extract(month from full_date) between 10 and 12 then substr(item_scan_timestamp, -4) || 'Q4' end quarter, r.store_id, p.full_date, r.sales_net_amt
from retailsalesfact r join purchasedate p on p.purchase_date_id = r.purchase_date_id
where (r.store_id, p.full_date) in (select r.store_id, max(p.full_date) full_date
from retailsalesfact r join purchasedate p on p.purchase_date_id = r.purchase_date_id
group by r.store_id)
union all
select case when extract(month from full_date) between 1 and 3 then substr(item_scan_timestamp, -4) || 'Q1'
when extract(month from full_date) between 4 and 6 then substr(item_scan_timestamp, -4) || 'Q2'
when extract(month from full_date) between 7 and 9 then substr(item_scan_timestamp, -4) || 'Q3'
when extract(month from full_date) between 10 and 12 then substr(item_scan_timestamp, -4) || 'Q4' end quarter, r.store_id, p.full_date, r.sales_net_amt
from retailsalesfact r join purchasedate p on p.purchase_date_id = r.purchase_date_id
where (r.store_id, p.full_date) in (select r.store_id, min(p.full_date) full_date
from retailsalesfact r join purchasedate p on p.purchase_date_id = r.purchase_date_id
group by r.store_id)
order by store_id, full_date, sales_net_amt;
select store_id, full_date, sales_net_amt
from retailsalesfact r join purchasedate p on p.purchase_date_id = r.purchase_date_id
order by store_id;
任何建议表示赞赏。

