按多列分组 select 另一列最大值小于特定值的记录

Group by multiple columns and select the records with the maximum values of another column which is less than a specific value

我有一个 SQL 问题。我有下表:

 ID A   B   C  
 1  A1  B1  C1  
 2  A1  B1  C2  
 3  A2  B2  C3  
 4  A1  B1  C3  
 5  A2  B2  C2  
 6  A3  B1  C1  
 7  A1  B1  C4  
 8  A2  B1  C1  

我想从每个 'A' 和 'B' 相同的组中 select 一行。例如,第 1、2、4 和 7 行构成一个组,其中 A = 'A1' & B = 'B1'。在这些组中,我想要 'C' 列中的最大值不大于 'C3' 的记录,因此在上面的组中记录 #4。

这是我正在寻找的结果集:

ID  A   B   C  
4   A1  B1  C3  
3   A2  B2  C3  
6   A3  B1  C1  
8   A2  B1  C1  

这可能会满足您的需求:

Select A, B, Max(C) as maxC
(
  Select *
  From SomeTable
  Where C <= 'C3'
) as nested
Group By A, B

您可以使用 CTE 和排名函数:

WITH CTE AS
(
    SELECT ID, A,   B,   C,
           RN = ROW_NUMBER() OVER (PARTITION BY A, B ORDER BY C DESC)
    FROM dbo.TableName
    WHERE C <= 'C3'
)
SELECT ID, A,   B,   C
FROM CTE
WHERE RN = 1

试试这个,

SELECT *
FROM   (SELECT *,
               Row_Number()
                 OVER (
                   PARTITION BY A, B
                   ORDER BY C DESC) AS RN
        FROM   #TEMP)A
WHERE  RN = 1 

试试这个,

 SELECT DISTINCT ID,A,
            B,C
  FROM  (SELECT Row_number()
            OVER(
              partition BY A, B
              ORDER BY id, c DESC)rn,
          *
   FROM   tabl1)p
 WHERE  rn IN( 1, 3 )
   AND id > 1