2015-03-19 106 views
1

我有一個非常奇怪的業務需求,我需要用下面兩個表來滿足前面的個股:SQL我們會根據修改日期

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

我會嘗試這樣的回答,當然我在選擇子查詢面色不那麼好,性能我猜...:

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 |