2017-07-04 36 views
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) 

回答

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

我只想做一個簡單的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)。

相關問題