如何获得产品今天和昨天价格的差异,并了解产品是否昨天可用?

时间:2015-02-16 08:15:23

标签: sql postgresql amazon-redshift

我有一张桌子" price_hist"在AmazonRedshift(Postgresql)中,每天有两个产品和价格数据,每天两次。我只想要每种产品每天的最新数据

以下示例是表

Country Product Price(string)   Created_On
US      001     $2,300     2015/02/16 00:46:20
US      001     $2,300     2015/02/16 13:27:12
DK      006     kr1,700    2015/02/16 00:46:20    
DK      006     kr1,700    2015/02/16 13:27:12 

US      002     $5,300     2015/02/15 00:46:20
US      002     $5,300     2015/02/15 13:27:12
US      001     $2,200     2015/02/15 00:46:20
US      001     $2,200     2015/02/15 13:27:12
DK      007     kr28       2015/02/15 00:46:20    
DK      007     kr28       2015/02/15 13:27:12 

US      001     $2,100     2015/02/14 00:46:20
US      002     $5,200     2015/02/14 13:27:12
DK      007     kr9,100    2015/02/14 00:46:20    
DK      007     kr9,100    2015/02/14 13:27:12

现在我想要一个查询,该查询应始终显示今天和昨天的价格差异数据以及产品标志,无论昨天是否可用。 要求输出:

Country Product P_today  p_yesterday p_change  flag   created_on
US      001     2300     2200           100    Both     2015/02/16 13:27:12
US      002     0        5300         -5300    Removed  2015/02/15 13:27:12
DK      006     1700     0             1700    Added    2015/02/16 13:27:12    
DK      007     0        9100         -9100    Removed  2015/02/15 13:27:12 

列P_Change - 显示今天和昨天的产品之间的价格变化。              flag - 创建一列以反映今日数据中添加的新产品以及已删除的数据。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

select country,product,P_today,P_yesterday, (P_today - P_yesterday) as P_change , 
    CASE 
    WHEN P_today > 0 and P_yesterday > 0 then 'both'
    WHEN P_today = 0 and P_yesterday > 0 then 'removed'
    WHEN P_today > 0 and P_yesterday = 0 then 'added'
    END
from
(select 
    isnull(q1.country,q2.country) as country,isnull(q1.product, q2.product) as product ,isnull(q1.price, 0) as P_today, isnull(q2.price,0) as P_yesterday
    from 
    (select * from product where created_on in (select max(created_on) from product where date_trunc('day', created_on) = '2015-02-16 00:00:00+00' group by product,country)) as q1 
    full outer join 
    (select * from product where created_on in (select max(created_on) from product where date_trunc('day', created_on) = '2015-02-15 00:00:00+00' group by product,country)) as q2 
    on q1.country = q2.country and q1.product = q2.product )

我测试了它,它给了我类似于你想要的东西,见下文:

 country | product | p_today | p_yesterday | p_change |  case   
---------+---------+---------+-------------+----------+---------
 US      | 001     |    2300 |        2300 |        0 | both
 US      | 002     |       0 |        2300 |    -2300 | removed
 DK      | 006     |     700 |           0 |      700 | added
 DK      | 007     |       0 |        2300 |    -2300 | removed

希望有所帮助。