基于日期的价格历史

时间:2014-10-09 22:23:08

标签: sql-server

要求将所有价格变动列为单一输出。

我的表格数据如下

我们打电话给PRICE_HIST表

Itemid  Price   Price_Change_Date
111A112 1,000.00    10/03/2014
111A114 1,111.00    10/03/2014
111A11  1,111.00    10/03/2014
111A111 1,000.00    10/03/2014
111A114 2,222.00    10/09/2014
111A111 2,222.00    10/09/2014

需要Query帮助才能获得如下输出。

Itemid  Last_Modified   Current_Price Last_Change Last_Change1 Last_Change2
111A112 10/03/2014      1,000.00      NA          NA           NA
111A11  10/03/2014      1,111.00      NA          NA           NA
111A114 10/09/2014      2,222.00      1,111.00    NA           NA
111A111 10/09/2014      2,222.00      1,000.00    NA           NA

首次使用者:-(无法格式化代码

1 个答案:

答案 0 :(得分:1)

您的问题已标记为MySQL。

这是一个 MySQL解决方案:

select itemid,
       max(price_date) as last_modified,
       max(case when rn = 1 then price end) as current_price,
       max(case when rn = 2 then price end) as last_change,
       max(case when rn = 3 then price end) as last_change1,
       max(case when rn = 4 then price end) as last_change2
from
(
select @rn := case
         when @itemid = itemid then
          @rn + 1
         else
          1
       end as rn,
       @itemid    := itemid    as itemid,
       price,
       price_date
  from price_hist
 cross join (select @rn := 0, @itemid := '') as t
 order by itemid, price_date desc
) x
group by itemid
order by last_modified, itemid

这使用变量来模仿其他数据库中可用的row_number()功能,基本上是在itemid上进行分区。然后,它使用条件聚合来旋转每个项目的4个最新价格。

如果您实际使用的是SQL Server,则可以使用row_number()

这是 SQL Server解决方案:

select itemid,
       max(price_date) as last_modified,
       max(case when rn = 1 then price end) as current_price,
       max(case when rn = 2 then price end) as last_change,
       max(case when rn = 3 then price end) as last_change1,
       max(case when rn = 4 then price end) as last_change2
from
(
select row_number() over (partition by itemid order by itemid, price_date desc) as rn,
       itemid,
       price,
       price_date
  from price_hist
) x
group by itemid
order by last_modified, itemid
相关问题