【问题标题】:Finding max and count in one join在一次连接中查找最大值和计数
【发布时间】:2017-12-07 07:34:35
【问题描述】:

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

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

)

【问题讨论】:

    标签: sql join sql-server-2012 maxdate


    【解决方案1】:

    你差点就吃完了:

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

    【讨论】:

      【解决方案2】:

      我会用一个简单的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)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-12
        • 1970-01-01
        • 2020-12-23
        • 2021-04-02
        • 2018-05-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多