SQL 嵌套查询和使用 MAX 提取最近的交易 and/or 评论

SQL nested query and use of MAX to extract most recent transaction and/or comment

我们有一个 SQL 数据库 table 记录客户评论 (ARCMM)。我想提取每个客户的最新评论。一些客户没有任何评论(即在 ARCMM 中没有条目)。 客户的最新评论将具有最新日期(字段 DATEENTR),并且对于该日期,字段 CNTUNIQ 具有最高值。下面的查询没有按预期工作。最佳解决方案?

查询:

SELECT
----- Customer masterfile
[ARCUS].[IDCUST],
[ARCUS].[NAMECUST],
----- Customer comments
[ARCMM].[CNTUNIQ],
[ARCMM].[DATEENTR],
[ARCMM].[TEXT]
FROM
[ARCUS]  
----- Table ARCMM roto ID AR0021  Customer Comments -----
   LEFT JOIN [ARCMM]
   ON
   [ARCMM].[IDCUST] = [ARCUS].[IDCUST]
   AND
   [ARCMM].[CNTUNIQ] =              
                  (  
                   SELECT MAX([CNTUNIQ])
                   FROM [ARCMM] ARCMMcopy2
                   WHERE 
                   [ARCMMcopy2].[IDCUST] = [ARCMM].[IDCUST]   
                   AND
                   [ARCMM].[DATEENTR] =  
                                       (
                                        SELECT MAX([DATEENTR])    
                                        FROM [ARCMM] ARCMMcopy1
                                        WHERE
                                        [ARCMMcopy1].[IDCUST]  = [ARCMM].[IDCUST]
                                        )
                   )    

示例 table ARCMM 数据:

IDCUST  DATEEENTR  CNTUNIQ  TEXT
Bob     20200311        1   Bob has woken up
Bob     20200311        2   Bob is having breakfast
Bob     20200629        1   Bob is sleeping         <most recent for IDCUST Bob
Jill    20200128        1   Order started
Jill    20200218        1   Order sent
Jill    20200218        2   Goods received
Jill    20200218        3   Goods counted
Jill    20200325        1   Invoice received
Jill    20200325        2   Invoice processed       <most recent for IDCUST Jill
Alison  20200225        1   Swimming
Alison  20200425        1   Walking
Alison  20200425        2   Running
Alison  20200425        3   Running
Alison  20200425        4   Sprinting
Alison  20200425        5   Jogging
Alison  20200425        6   Stopped                 <most recent for IDCUST Alison

我的 SQL 查询尝试的结果:

IDCUST   NAMECUST          CNTUNIQ   DATEENTR   TEXT
Bob      Bob Brown         Null      Null       Null
Jill     Jill Jenkins      Null      Null       Null
Alison   Alison Allpress   6         20200425   Stopped 

期望的结果:

IDCUST   NAMECUST          CNTUNIQ   DATEENTR   TEXT
Bob      Bob Brown         1         20200629   Bob is sleeping
Jill     Jill Jenkins      2         20200325   Invoice processed
Alison   Alison Allpress   6         20200425   Stopped 

如果您的数据库支持 window 函数,您可以在 left join 中使用 row_number()

SELECT
    c.[IDCUST],
    c.[NAMECUST],
    m.[CNTUNIQ],
    m.[DATEENTR],
    m.[TEXT]
FROM [ARCUS] c 
LEFT JOIN (
    SELECT 
        m.*, 
        ROW_NUMBER() OVER(
            PARTITION BY [IDCUST] 
            ORDER BY [DATEENTR] DESC, [CNTUNIQ] DESC
        ) rn
    FROM [ARCMM] m
) m ON m.[IDCUST] = c.[IDCUST] and m.rn = 1