Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择具有匹配日期或最新日期记录的_Sql_Left Join_Maxdate - Fatal编程技术网

Sql 选择具有匹配日期或最新日期记录的

Sql 选择具有匹配日期或最新日期记录的,sql,left-join,maxdate,Sql,Left Join,Maxdate,这里有两张桌子 ItemInfo Id Description 1 First Item 2 Second Item 下面是SQL查询 SELECT i.Id, Price, StartDate, EndDate FROM Itemsinfo i LEFT JOIN ItemInfoHistory ih ON i.id= ih.ItemsMasterId AND CONVERT(DATE, GETDATE()) >= StartDate AND ( CONVERT(

这里有两张桌子

ItemInfo

Id  Description
1   First Item  
2   Second Item
下面是SQL查询

SELECT i.Id, Price, StartDate, EndDate 
FROM Itemsinfo i 
LEFT JOIN ItemInfoHistory ih ON i.id= ih.ItemsMasterId AND  CONVERT(DATE, GETDATE()) >= StartDate AND ( CONVERT(DATE, GETDATE()) <= EndDate OR EndDate IS NULL)
对于第二项,我想从历史记录表中获取最新记录,如下所示

Id  Price   StartDate   EndDate
1   50      2020-09-16  NULL
2   55      2020-09-26  NULL

提前感谢。

最有效的方法可能是两次连接。假设“最新”记录的
EndDate
值为
NULL
,则:

SELECT i.Id,
       COALESCE(ih.Price, ih_last.Price) as Price,
       COALESCE(ih.StartDate, ih_last.StartDate) as StartDate,
       COALESCE(ih.EndDate, ih_last.EndDate) as EndDate
FROM Itemsinfo i LEFT JOIN
     ItemInfoHistory ih
     ON i.id = ih.ItemsMasterId AND 
        CONVERT(DATE, GETDATE()) >= StartDate AND
        (CONVERT(DATE, GETDATE()) <= EndDate OR EndDate IS NULL) LEFT JOIN
     ItemInfoHistory ih_last
     ON i.id = ih_last.ItemsMasterId AND 
        ih_last.EndDate IS NULL;
选择i.Id,
合并(ih.Price,ih_last.Price)作为价格,
合并(ih.StartDate,ih_last.StartDate)为StartDate,
合并(ih.EndDate,ih_last.EndDate)作为结束日期
从Itemsinfo我离开了JOIN
ItemInfoHistory ih
在i.id=ih.ItemsMasterId和
转换(日期,GETDATE())>=StartDate和
(转换(日期,GETDATE())
Id  Price   StartDate   EndDate
1   50      2020-09-16  NULL
2   55      2020-09-26  NULL
SELECT i.Id,
       COALESCE(ih.Price, ih_last.Price) as Price,
       COALESCE(ih.StartDate, ih_last.StartDate) as StartDate,
       COALESCE(ih.EndDate, ih_last.EndDate) as EndDate
FROM Itemsinfo i LEFT JOIN
     ItemInfoHistory ih
     ON i.id = ih.ItemsMasterId AND 
        CONVERT(DATE, GETDATE()) >= StartDate AND
        (CONVERT(DATE, GETDATE()) <= EndDate OR EndDate IS NULL) LEFT JOIN
     ItemInfoHistory ih_last
     ON i.id = ih_last.ItemsMasterId AND 
        ih_last.EndDate IS NULL;