sql查询生效日期

时间:2014-06-06 10:23:47

标签: sql sql-server stored-procedures

我想获得整个月购买饮料的报告,但饮料的价格可能会在一个月内的任何时间发生变化,我想在价格变动的情况下获得一个月的报告

我有两张桌子

SELECT  [ID]
      ,[DrinkID]
      ,[UserID]
      ,[qty]
      ,[DateTaken]
  FROM [Snacks].[dbo].[DrinkHistory]

SELECT  [ID]
      ,[DrinkID]
      ,[UserID]
      ,[qty]
      ,[DateTaken]
  FROM [Snacks].[dbo].[DrinkHistory]

[DrinkHistory] ​​

ID             DrinkID     UserID          qty         DateTaken
----------------------------------------------------------------------    
1               1               1               1           2014-05-10  
2               1               1               2           2014-05-15  
3               2               1               1           2014-06-01  
4               2               1               4           2014-06-01  
5               1               1               3           2014-05-20  
6               1               1               4           2014-05-30  

[DrinkPricesEffect]

PriceID        DrinkID         DrinkPrice      PriceEffectiveDate         IsCurrent
-----------------------------------------------------------------------------------
1               1               10.00             2014-05-01    1
2               1               20.00             2014-05-20    1
3               2               9.00              2014-06-01    1 
4               2               8.00              2014-01-01    1
5               1               30.00             2014-05-25    1
6               1               40.00             2014-05-28    1

我希望在2014-05-1至2014-05-31之间获得结果

DrinkId Qty    Price    DateTaken       PriceEffectiveDate
-----------------------------------------------------------------------
1   1       10      2014-05-10          2014-05-01  
1   2       10      2014-05-15          2014-05-01  
1   3   20      2014-05-20          2014-05-20  
1   4   40      2014-05-30          2014-05-28  

有没有人可以给我一些想法或为我写一些查询?

2 个答案:

答案 0 :(得分:1)

如果您的饮料价格可以在一个月内的任何时间更改,您可以另外保存每次购买的价格。我会在表[DrinkHistory]中添加一列[PricePaid]。

将记录添加到[DrinkHistory]时,此时饮料的价格已知,但稍后可能会更改,因此您将当前价格保存到历史记录中......

然后,您可以显示整个[DrinkHistory] ​​

SELECT * FROM DrinkHistory;

答案 1 :(得分:0)

这应该有效:

Select 
    DH.DrinkId,
    DH.Qty,
    DPE.DrinkPrice AS Price,
    DH.DateTaken,
    DPE.PriceEffectiveDate
FROM DrinkHistory DH
JOIN DrinkPricesEffect DPE ON DPE.PriceID = 
(
  Select Top 1 PriceID FROM
  (
    Select PriceID,RANK() OVER(ORDER BY PriceEffectiveDate DESC ) AS rnk
    FROM  DrinkPricesEffect
    WHERE DH.DrinkId = DrinkId AND
          DH.DateTaken >= PriceEffectiveDate

  )SubQ WHERE rnk = 1
) 
WHERE DH.DateTaken Between '2014-05-01' AND '2014-05-30'

在这里您可以找到SQL Fiddle链接:http://sqlfiddle.com/#!6/5f8fb/26/0