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

时间:2017-07-04 01:16:22

标签: sql join sql-server-2012 maxdate

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

我有两个表:表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的最大deliveryDate添加到表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 ) 

2 个答案:

答案 0 :(得分:2)

你几乎拥有它:

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

答案 1 :(得分:1)

我只想使用简单的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)。