2017-08-29 65 views
2

之間的最小日期表我有2個表: @Temdate1更新2臺

+------+------------+---------------+--------+ 
| Year | Entry_Date | DeliveryMonth | Symbol | 
+------+------------+---------------+--------+ 
| 2016 | 2016-01-07 | June   | ABC | 
| 2015 | 2015-01-06 | June   | ABC | 
| 2014 | 2014-01-05 | June   | ABC | 
| 2016 | 2016-03-05 | Sep   | CDE | 
| 2015 | 2015-03-04 | Sep   | CDE | 
| 2014 | 2014-03-03 | Sep   | CDE | 
+------+------------+---------------+--------+ 

AllProducts

+-----------------+---------------+--------+ 
|  Date  | DeliveryMonth | Symbol | 
+-----------------+---------------+--------+ 
| 2016-01-07  | June   | ABC | 
| 2016-01-08  | June   | ABC | 
| 2016-01-09  | June   | ABC | 
| 2016-01-10  | June   | ABC | 
| 2015-01-01  | June   | ABC | 
| 2015-01-02  | June   | ABC | 
| 2015-01-03  | June   | ABC | 
| 2014-01-05  | June   | ABC | 
+-----------------+---------------+--------+ 

結果我要尋找更新的表@ Temdate1:​​

+------+------------+---------------+--------+ 
| Year | Entry_Date | DeliveryMonth | Symbol | 
+------+------------+---------------+--------+ 
| 2016 | 2016-01-07 | June   | ABC | 
| 2015 | 2015-01-01 | June   | ABC | 
| 2014 | 2014-01-05 | June   | ABC | 
| 2016 | 2016-03-05 | Sep   | CDE | 
| 2015 | 2015-03-04 | Sep   | CDE | 
| 2014 | 2014-03-03 | Sep   | CDE | 
+------+------------+---------------+--------+ 

我有這個查詢來找到最小的(ear最簡單的)給定年份和給定產品的日期。有了這個查詢如何更新Temdate1與最早的日期,當它沒有最早的日期?

SELECT 
Year 
,CASE 
    WHEN MIN([Date])<entry_date THEN MIN([Date]) 
    ELSE entry_date 
END AS MDate 
FROM @TempDate1 a 
INNER JOIN AllProducts b on a.DeliveryMonth =b.DeliveryMonth AND a.Symbol = b.Symbol 
GROUP BY Year,entry_date 
+0

提供的數據結構和數據樣本 – Horaciux

+0

所以你問如何將用戶的輸出你查詢更新Temdate1?你能告訴我們表Temdate1的結構嗎? – Lamar

+0

您應該能夠在更新聲明中使用此case子句。 – Eli

回答

3

看來你犯了一個錯字在預期的結果,也許是我

Update a 
    set Entry_Date = case when a.Entry_Date> b.Date then b.Date else a.Entry_Date end 
from 
    @Tempdate1 a 
inner join 
    @AllProducts b 
    on b.Symbol = a.Symbol 
    and b.DeliveryMonth = a.DeliveryMonth 
    and year(b.[Date]) = a.Year 

http://rextester.com/AQXR21093

+0

@JulGreen - 這就是我所說的CASE聲明可以在這裏使用。 – Eli

+0

@Horaciux非常感謝你這是我正在尋找,無法弄清楚。在'Entry_Date =' – JulGreen

+0

之後,我將整個陳述放在括號內。我剛糾正了http://rextester.com/AQXR21093中的錯字 – Horaciux