Sql 在一个联接中查找max和count

Sql 在一个联接中查找max和count,sql,join,sql-server-2012,maxdate,Sql,Join,Sql Server 2012,Maxdate,这个问题可能有一个简单的解决方案,但不幸的是,我无法解决它 我有两张桌子:A桌和B桌 Table A Table B ------------------- ------------------------------ Id NoOfItems Id itemNo deliveredDate X1 3

这个问题可能有一个简单的解决方案,但不幸的是,我无法解决它

我有两张桌子:A桌和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的最大deliveredDate添加到表A中,但前提是表B中交付的项目数等于表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) 
你差点就成功了:

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

我只需通过一个简单的
加入
分组即可:

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

我只需通过简单的
连接
分组即可:

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