在SQL Server中通过最新日期获取唯一ID(FK)

时间:2019-03-13 03:56:47

标签: sql sql-server sql-server-2008 select distinct

我目前正在处理一个查询,该查询需要根据创建的最新日期来区分ID。

这是我的图

|  ID  |    ModelID     |    LocationId   |  DateCreated  |
|------+----------------+-----------------+---------------|
|   1  |       1        |        5        |   02/03/2019  |
|   2  |       2        |      null       |   01/14/2019  |
|   3  |       2        |        0        |   02/03/2019  |
|   4  |       2        |        5        |   12/30/2018  |
|   5  |       4        |        3        |   01/10/2019  |
|   6  |       3        |        5        |   02/14/2019  |
|   7  |       2        |        5        |   03/13/2019  |

所以我的目标是区分ModelId,但仍然显示LocationId is null or equals to 0,然后如果LocationId仍然相同,请获取最新的DateCreated并将其显示在列表中

所需的输出:

    |  ID  |    ModelID     |    LocationId   |  DateCreated  |
    +------+----------------+-----------------+---------------+
    |   1  |       1        |        5        |   02/03/2019  |
    |   2  |       2        |      null       |   01/14/2019  |<-still show
    |   3  |       2        |        0        |   02/03/2019  |<-still show
    |   4  |       2        |        5        |   03/13/2019  |<-The Latest
    |   5  |       4        |        3        |   01/10/2019  |
    |   6  |       3        |        5        |   02/14/2019  |

这是我当前的SQL查询:

SELECT 
    a.ModelID, a.LocationId,
    (SELECT TOP 1 
         CONVERT(NVARCHAR, DateCreated, 101) 
     FROM 
         db.DeliveryDates 
     WHERE
         isDeleted = 0 
         AND DeliveryId = a.DeliveryId) AS DateCreated,
FROM 
    db.DeliveryCarInfo a
WHERE
    a.isDeleted = 0

2 个答案:

答案 0 :(得分:1)

您可以尝试以下查询。联盟将有助于获得理想的结果。

with cte
as 
(
SELECT a.ModelID 
        , a.LocationId 
        , (Select top 1 convert(nvarchar,DateCreated,101) from 
        db.DeliveryDates where isDeleted=0 and DeliveryId=a.DeliveryId) as 
         DateCreated
FROM db.DeliveryCarInfo a
WHERE a.isDeleted = 0
)
select ModelID, LocationId, DateCreated 
from cte 
where isnull(LocationId, 0) = 0

union

select ModelID, LocationId, max(DateCreated) as DateCreated
from cte
where isnull(LocationId, 0) != 0
group by ModelID, LocationId

答案 1 :(得分:1)

请尝试这个。

SELECT A.* from @tbl A
INNER JOIN
(
    SELECT ModelId,Max(DateCreated) As CreateDate from @tbl Group By ModelId
) As B
    ON B.ModelId = A.ModelId
    AND A.DateCreated = B.CreateDate

 UNION 

 Select * from @tbl A
 WHERE LocationId IS NULL OR LocationId = 0