SQL根据修改日期获取以前的库存

时间:2015-03-19 06:13:45

标签: sql sql-server sql-server-2008-r2

我有一个非常奇怪的业务需求,我需要使用以下两个表来实现:

STOCK_TB (As of 20150319)

PRODUCT_ID STOCK_QTY 
   A          20
   B          15

STOCK_MODIFIED_TB

PRODUCT_ID MODIFIED_QTY MODIFIED_DATE_FROM MODIFIED_DATE_TO
   A          10             20150315         20150318
   B          -5             20150314         20150316
   A          -2             20150314         20150316

STOCK_TB表示当前的库存库存,而STOCK_MODIFIED_TB表示在日期范围内修改的库存数量。我需要选择之前日期的股票结果。假设结果在20150319检索日期20150314-20150319。这就是结果应该是这样的:

DATE    PRODUCT_ID  STOCK_QTY
20150314    A         18
20150314    B         10
20150315    A         28
20150315    B         10
20150316    A         28
20150316    B         10
20150317    A         30
20150317    B         15
20150318    A         30
20150318    B         15
20150319    A         20
20150319    B         15

换句话说,以前日期的股票将根据STOCK_MODIFIED_TB中给出的日期范围加/减

在没有光标的情况下选择这样的数据吗?

1 个答案:

答案 0 :(得分:1)

我会尝试这个答案,当然我的子查询在选择中看起来不太好,我猜...:

<强> SQLFIddleExample

SELECT cast(a.Date as date) Date,
       st.PRODUCT_ID,
       st.STOCK_QTY + isnull((SELECT SUM(MODIFIED_QTY)
                       FROM STOCK_MODIFIED_TB
                      WHERE MODIFIED_DATE_FROM <= CONVERT(VARCHAR(10), a.Date, 112)
                      AND MODIFIED_DATE_TO >= CONVERT(VARCHAR(10), a.Date, 112)
                      AND PRODUCT_ID = st.PRODUCT_ID ),0) STOCK_QTY
FROM STOCK_TB st,
 (select DATEADD(day, number, '2015-01-01') Date 
from master..spt_values 
where type = 'p' ) a
WHERE a.Date between '2015-03-14' and '2015-03-19' 
ORDER BY a.Date, st.PRODUCT_ID 

结果:

|       Date | PRODUCT_ID | STOCK_QTY |
|------------|------------|-----------|
| 2015-03-14 |          A |        18 |
| 2015-03-14 |          B |        10 |
| 2015-03-15 |          A |        28 |
| 2015-03-15 |          B |        10 |
| 2015-03-16 |          A |        28 |
| 2015-03-16 |          B |        10 |
| 2015-03-17 |          A |        30 |
| 2015-03-17 |          B |        15 |
| 2015-03-18 |          A |        30 |
| 2015-03-18 |          B |        15 |
| 2015-03-19 |          A |        20 |
| 2015-03-19 |          B |        15 |