0

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

我有两个表:表 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 ) 

)

4

2 回答 2

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) 
于 2017-07-04T01:48:11.500 回答
1

我会用一个简单的joinand来做到这一点group 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)。

于 2017-07-04T03:22:53.160 回答