sql查询从不同的表中获取最大日期

时间:2012-03-08 22:30:40

标签: sql

好吧,我在一个表中有一个TankID和一个UnitNumber,在另一个表中有一个ExpiredDate,但是该表有相同tankID的多个过期日期,我只想要max(ExpiredDate)。

    TankID    UnitNumber   ExpiredDate
    20666   107            2009-08-31 00:00:00
    20666   107            2010-08-31 00:00:00
    20666   107            2011-08-31 00:00:00
    20666   107            2012-08-31 00:00:00
    20666   107            NULL

现在我只想回来

20666 107 2012-08-31

我试着这样做:

        select  tanks.TankID, tanks.UnitNumber, MAX(Table2.ExpireDate)
        from Tanks 
        join Table2 on Tanks.TankID = Table2.TankID
        where CompanyID = '1111'
        and   Tanks.TankID = '22222'
        order by Tanks.TankID

这显然不起作用,有人知道怎么做吗?感谢

3 个答案:

答案 0 :(得分:0)

尝试

SELECT tanks.tankId, tanks.unitNumber, (SELECT MAX(table2.ExpiraDate) FROM table2 WHERE table2.tankID = tanks.tankID) AS max_expire_date
FROM tanks
where CompanyID = '1111'
and   Tanks.TankID = '22222'
order by Tanks.TankID

答案 1 :(得分:0)

    select  tanks.TankID, tanks.UnitNumber, 
           (select MAX(Table2.ExpireDate) from Table2 where table2.TankID = Tanks.TankID) ExpireDate
    from Tanks
    where CompanyID = '1111'
    and   Tanks.TankID = '22222'
    order by Tanks.TankID

    select  tanks.TankID, tanks.UnitNumber, maxExpireDate.ExpireDate
    from Tanks join
       (
          select TankID, MAX(Table2.ExpireDate) ExpireDate 
            from Table2 
            group by TankID
       ) maxExpireDate
       on Tanks.TankID = maxExpireDate.TankID
    where CompanyID = '1111'
    and   Tanks.TankID = '22222'
    order by Tanks.TankID

答案 2 :(得分:0)

我正在粘贴两种方法来做到这一点。两个查询以不同的方式执行相同的操作。我用模拟数据设置了一个表变量,这样你就可以在本地数据库(或任何地方)上测试它,看看它是否有效。

DECLARE @Tanks TABLE
(
    CompanyId INT NOT NULL,
    TankId INT NOT NULL,
    UnitNumber INT NOT NULL
)

DECLARE @Expirations TABLE
(
    TankId INT NOT NULL,
    ExpiredDate DATETIME NULL
)

INSERT @Tanks
(
    CompanyId
    , TankId
    , UnitNumber
)
VALUES
    (1111, 22222, 107)

INSERT @Expirations
(
    TankId
    , ExpiredDate
)
VALUES
    (22222, '2009-08-31 00:00:00')
    , (22222, '2010-08-31 00:00:00')
    , (22222, '2011-08-31 00:00:00')
    , (22222, '2012-08-31 00:00:00')
    , (22222, NULL)

SELECT
    Tanks.TankId
    , Tanks.UnitNumber
    , Expiration.MaxExpiredDate
FROM @Tanks Tanks
CROSS APPLY
(
    SELECT MAX(E.ExpiredDate) MaxExpiredDate FROM @Expirations E WHERE E.TankId = Tanks.TankId
) Expiration
WHERE Tanks.CompanyId = 1111 AND Tanks.TankId = 22222

SELECT
    Tanks.TankId
    , Tanks.UnitNumber
    , MAX(Expirations.ExpiredDate) ExpiredDate
FROM @Tanks Tanks
LEFT JOIN @Expirations Expirations
    ON Expirations.TankId = Tanks.TankId
WHERE Tanks.CompanyId = 1111 AND Tanks.TankId = 22222
GROUP BY Tanks.TankId, Tanks.UnitNumber