我在Oracle中有一个表,其中包含文章的价格和日期,但是我需要上个月和当月的文章价格才能看到差异。
我需要通过上个月作为参数并获取数据
示例:
+---------+-------+------------+
| article | price | date |
+---------+-------+------------+
| cup | 3.5 | 02/06/2018 |
+---------+-------+------------+
| cup | 3.7 | 04/07/2018 |
+---------+-------+------------+
| cup | 3.8 | 04/08/2018 |
+---------+-------+------------+
预期:
所选月份:07
+---------+--------------+-------------+----------+----------+
| article | current_price|current_month|last_price|last_mont |
+---------+--------------+-------------+----------+----------+
| cup | 3.7 | 07/2018 | 3.5 | 06/2018 |
+---------+--------------+-------------+----------+----------+
答案 0 :(得分:0)
您可以使用以下SQL语句:
select article,
max(decode(to_char("date",'mm/yyyy'),to_char(sysdate,'mm/yyyy'),nvl(price,0)))
as current_price,
to_char(sysdate,'mm/yyyy') as current_month,
max(decode(to_char("date",'mm/yyyy'),to_char(add_months(sysdate,-1),'mm/yyyy'),
nvl(price,0)))
as last_price,
to_char(add_months(sysdate,-1),'mm/yyyy') as last_month
from articles
where article = 'cup'
group by article;
ARTICLE CURRENT_PRICE CURRENT_MONTH LAST_PRICE LAST_MONTH
cup 3,70 07/2018 3,50 06/2018
假设sysdate(当前日期)介于01/07/2018 - 31/07/2018
(格式为dd/mm/yyyy
)
答案 1 :(得分:0)
假设用户指定了日期,则以下内容将获取该日期的最后两个日期和价格:
select article_id,
max(case when seqnum = 1 then price end) as current_price,
max(case when seqnum = 1 then date end) as current_date,
max(case when seqnum = 2 then price end) as last_price,
max(case when seqnum = 2 then price end) as last_date
from (select e.*,
row_number() over (partition by article_id order by date desc) as seqnum
from examples e
where e.date <= :date
) e
group by article_id;