不对称列 - 选择最新给定值

时间:2013-07-26 16:40:28

标签: sql sql-server sql-server-2008 tsql

使用的版本:Microsoft SQL Server Management Studio,SQL Server 2008

我正面临着由不对称列引起的令人沮丧的问题。基本上,我想计算折扣对给定现货价格的影响。两者都在同一个表 pricevalues 中设置为索引。现货价格为每周5天,而折扣仅在更新当天说明。所以,例如:

价格值(priceindex,price,pricingate)

     PRICEINDEX             PRICE            PRICEDATE              
-------------------- ------------------ ------------------
DISCOUNT_INDEX_ID   |       15.5       |    2013-02-26
DISCOUNT_INDEX_ID   |       10.5       |    2013-04-05
DISCOUNT_INDEX_ID   |       16.0       |    2013-07-10
SPOT_INDEX_ID       |       356.5      |    2013-07-22
SPOT_INDEX_ID       |       355.0      |    2013-07-23
SPOT_INDEX_ID       |       354.6      |    2013-07-24
SPOT_INDEX_ID       |       357.0      |    2013-07-25
SPOT_INDEX_ID       |       358.5      |    2013-07-26

如果要使用最新给定的(相对于现货价格的PRICEDATE)折扣PRICE,我如何才能最好地计算SPOT_INDEX_ID和DISCOUNT_INDEX_ID的PRICE's与SPOT_INDEX_ID之间的差异?

例如,2013-07-22的现场折扣为 16.0 (2013-07-10),而2013-05-15的现场折扣为 10.5 (2013-04-05)2013-03-03现场折扣 15.5 (2013-02-26)

我只知道当PRICEDATE与DISCOUNT_INDEX_ID和SPOT_INDEX_ID匹配时如何做,所以:

SELECT 
(pv1.price - pv2.price) AS 'Total Price',
pv1.price AS 'Spot Price',
pv2.price AS 'Discount'
FROM 
pricevalues pv1, pricevalues pv2
WHERE
pv1.priceindex = 'SPOT_INDEX_ID' AND 
pv1.pricedate = pv2.pricedate AND
pv2.priceindex = 'DISCOUNT_INDEX_ID'

这当然不可能在折扣索引中存在这些巨大差距,所以当日期不匹配时,我如何获得最新给定折扣的价值?

编辑:我希望输出看起来如下:

    PRICEDATE        SPOT_INDEX         DISCOUNT_INDEX      SPOT_PRICE      
---------------- ------------------- --------------------- -----------   --->>>
   2013-07-26   |   SPOT_INDEX_ID   |  DISCOUNT_INDEX_ID  |   358.5   |

 DISCOUNT_PRICE       TOTAL_PRICE             
---------------- -------------------
      16.0      |       342.5       |

3 个答案:

答案 0 :(得分:0)

您可以在给定日期的变量中获取折扣价格,然后在主查询中使用它。这是样本:

Declare @Discount_Price money
select Max(pricedate),@Discount_Price=Price from pricevalues where PriceIndex='DISCOUNT_INDEX_ID' group by Price having Price=Max(PriceDate)    
SELECT 
    (pv1.price - @Discount_Price) AS PriceDiff,
    pv1.price AS 'Spot Price',
    @Discount_Price AS 'Discount'
FROM 
    pricevalues pv1 
WHERE
    pv1.priceindex = 'SPOT_INDEX_ID'

答案 1 :(得分:0)

如果您只想返回一条记录,这将有效:

DECLARE @date DATE = GETDATE()
SELECT TOP 1 a.PRICEDATE, b.PRICE 'Spot', a.PRICE 'Discount', b.Price - a.Price 'Total'
FROM #Table1 a
JOIN (SELECT *,ROW_NUMBER() OVER (PARTITION BY PRICEINDEX ORDER BY PRICEDATE DESC)'RowRank'
      FROM #Table1
      WHERE PRICEINDEX = 'SPOT_INDEX_ID'
          AND PRICEDATE <= @date
      )b         
  ON b.RowRank = 1
WHERE a.PRICEINDEX = 'DISCOUNT_INDEX_ID'
       AND a.PRICEDATE <= @date 
ORDER BY a.PRICEDATE DESC

GETDATE()更改为您的查询日期。

我不确定您对PRICEDATE的要求,也许应该是b.PRICEDATE,或者只是@date

答案 2 :(得分:0)

我通过SQL中的FETCHES和Excel中的处理组合解决了这个问题,我也处理了折扣索引中的差距。