sql - 如何比较Oracle中一组行的最大和最小日期的列值?
问题描述
给定一个看起来像这样的表,我将如何创建另一个获取此数据的查询,比较该 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;
任何建议表示赞赏。
解决方案
您可以使用该KEEP
子句,GROUP BY
因为您希望每个商店有一条记录,如下所示:
select store_id,
case when max(SALES_NET_AMT) keep (dense_rank first order by FULL_DATE desc)
> max(SALES_NET_AMT) keep (dense_rank first order by FULL_DATE)
then 'Increased'
else 'Decreased'
end as result
from your_Table t
group by store_id
推荐阅读
- mobile-safari - HTML 的最佳设置, 对于移动设备
- android - 如何查询安卓设备的视频功能?
- javascript - 倒计时后从 getUserMedia 释放网络摄像头和麦克风
- python-3.x - Python 3.7.0 和 Ansible 2.6:ModuleNotFoundError:没有名为“_curses”的模块
- php - 存储 MikroTik IP 记帐数据的更有效方式?
- java - 在 Java 中存储键值
- c# - James Montemagno 的 Xam.Plugins.Settings 似乎没有保存我的设置
- default-value - Programmatically set default column values based on folder in SharePoint Online
- linux - 如何获取plesk系统用户使用php命令行的权限
- java - 如果firebase中有相同的值,如何创建条件