我試圖找到一種有效的方式,選擇從現有的表中的第一個相關值,如Excel的VLOOKUP(, , , TRUE)
功能會。這是我的,但如果@tableWithData
與@requiredDates
相比非常大,則此代碼效率可能非常低。我覺得我錯過了一些東西。有沒有寫這更好的辦法:SQL相當於Excel的近似VLOOKUP(第一相關值)沒有嵌套查詢
DECLARE @requiredDates TABLE
(requiredDate datetime)
INSERT INTO @requiredDates VALUES ('2014-01-01');
INSERT INTO @requiredDates VALUES ('2014-01-15');
INSERT INTO @requiredDates VALUES ('2014-02-01');
INSERT INTO @requiredDates VALUES ('2014-02-15');
DECLARE @tableWithData TABLE
(respectiveDate datetime,
associatedValue int
)
INSERT INTO @tableWithData VALUES ('2014-01-01', 1);
INSERT INTO @tableWithData VALUES ('2014-02-01', 2);
SELECT
lookupTable.requiredDate,
dataTable.associatedValue
FROM @tableWithData as dataTable RIGHT JOIN
(
/*Create table which maps the requiredDates -> maxDate highest available date */
SELECT
dates.requiredDate,
MAX(data.respectiveDate) as maxDate/*,
data.associatedValue*/
FROM @requiredDates as dates JOIN @tableWithData as data
ON dates.requiredDate >= data.respectiveDate
GROUP BY dates.requiredDate
) as lookupTable
on lookupTable.maxDate = dataTable.respectiveDate
注:我使用的MS Server 2005中,但還希望更通用的SQL實現,如果有一個。