在一个连接中查找最大值和计数

Finding max and count in one join

这个问题可能有一个简单的解决方案,但不幸的是,我想不通。

我有两个 table:Table A 和 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

所以我需要的是将每个 Id 的最大交付日期添加到 table A,但前提是 Table B 中的交付项目数等于 Table A 中的 NoOfItems .

到目前为止我已经写了这个查询:

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 ) 

)

你几乎成功了:

;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) 

我只想用一个简单的 joingroup by:

select a.*,
       (case when b.cnt = a.noofitems then b.deliveredDate end)
from a join
     (select b.id, count(*) as cnt, max(deliveredDate) as deliveredDate
      from b
      group by b.id
     ) b;
     on a.id = b.id;

不清楚您是否要将交付日期分配给所有行,并为匹配的行分配 NULL 值(如上述查询)。或者,如果您想过滤掉不匹配的行(在这种情况下使用 where)。