Search code examples
sqljoinsql-server-2012maxdate

Finding max and count in one join


This problem might have an easy solution, but unfortunately, I can't figure it out.

I have two tables: Table A and Table B

Table A                         Table B
-------------------             ------------------------------    
Id      NoOfItems               Id     itemNo         deliveredDate
X1          3                   X1       1              2017-07-01
                                X1       2              2017-07-02
                                X1       3              2017-07-03

So what I need is to add the maximum deliveredDate of each Id to table A, but only if the number of delivered items in Table B equals NoOfItems in Table A.

So far I have written this query:

SELECT  *
FROM    A
OUTER APPLY
    (
    SELECT  TOP 1 *
    FROM    B
    WHERE   A.Id =B.Id
    ORDER BY
            B.DeliveredDate DESC
    ) s
    where A.NoOfItems= (select count(1) from B ) 

)


Solution

  • You almost had it:

    ;with A as
    (select 1 ID, 3 NoOfItems
    union all select 2 ID, 2 NoOfItems
    union all select 3 ID, 1 NoOfItems
    )
    , B as
    (select 1 id, 1 itemno, '2017-07-01' deliveredDate
    union all select 1, 2, '2017-07-02'
    union all select 1, 3, '2017-07-03'
    union all select 2, 1, '2017-08-02'
    union all select 2, 2, '2017-08-03'
    )
    SELECT  *
    FROM    A
    OUTER APPLY
        (
        SELECT  TOP 1 *
        FROM    B
        WHERE   A.Id =B.Id
        ORDER BY
                B.DeliveredDate DESC
        ) s
        where A.NoOfItems = (select count(1) from B WHERE B.id = A.ID)