sql嵌套查询并使用max提取最近的事务和/或注解

yptwkmov  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(370)

我们有一个记录客户评论的sql数据库表(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]
                                        )
                   )

样本表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
k4ymrczo

k4ymrczo1#

你可以用 row_number()left join ,如果数据库支持窗口函数:

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

相关问题