SELECT行值WHERE MAX()是GROUP BY查询中的列值

时间:2013-07-09 12:56:00

标签: sql sql-server tsql

我该如何选择?我可以创建用户定义的聚合函数

SELECT Max(A),(SELECT TOP 1 FROM TheGroup Where B=Max(A)) FROM MyTable

下面显示的MyTable

    A  B  C
--------------
    1  2  S
    3  4  S
    4  5  T
    6  7  T

我想要像这样的查询

SELECT MAX(A),(B Where A=Max(A)),C FROM MYTable GROUP BY C

我期待结果如下

 MAX(A)  Condition    C
-----------------------
   3        4         S
   6        7         T

6 个答案:

答案 0 :(得分:2)

 SELECT A,B,C FROM
     (SELECT *, ROW_NUMBER() OVER (PARTITION BY C ORDER BY A DESC) RN FROM MyTable)
 WHERE RN = 1

(此查询将始终每个C值只返回一行)

OR

WITH CTE_Group AS 
(
    SELECT C, MAX(A) AS MaxA
    FROM MyTable
    GROUP BY C
)
SELECT g.MaxA, t.B, g.C
FROM MyTable t
INNER JOIN CTE_Group g ON t.A = g.MaxA AND t.C = g.C

(如果有多个行具有相同的Max(A)值 - 此查询将返回所有这些行)

答案 1 :(得分:1)

SELECT Max(A)
FROM MyTable
Where B=(SELECT Max(A) FROM MyTable) 

更新

SELECT *
FROM MyTable
Where B=(SELECT Max(A) FROM MyTable) 

更新2:

SELECT DISTINCT A, B
FROM MyTable
Where A=(SELECT Max(A) FROM MyTable GROUP BY C) 

更新3:

好吧,我想我明白你现在正在寻找什么..这个怎么样:

SELECT *
FROM MyTable
Where A in (SELECT Max(A) FROM MyTable GROUP BY C) 

答案 2 :(得分:1)

SELECT t1.*
FROM YourTable t1 
Left Outer Join YourTable t2 on t1.C=t2.C AND t1.A < t2.A
WHERE t2.A is null

答案 3 :(得分:1)

WITH
  cte AS
(
  SELECT 
    ROW_NUMBER() OVER (ORDER BY cola desc) AS Rno,
    *
  FROM
    tbl
)
SELECT top 1
cola,colb
FROM
  cte
order by Rno

然后试一试:

    WITH
  cte AS
(
  SELECT 
    ROW_NUMBER() OVER (PARTITION BY col3 ORDER BY col1 desc) AS Rno,
    *
  FROM
    tbl

)
SELECT 
col1,col2,col3
FROM
  cte
WHERE Rno=1

答案 4 :(得分:1)

怎么样:

    SELECT *
    FROM MyTable    
    WHERE A IN (SELECT MAX(A) FROM MyTable GROUP BY C)

答案 5 :(得分:1)

尝试以下查询:

SELECT TABLE1.A , TABLE2.B , TABLE1.C
FROM 
(
    SELECT MAX(A) AS A,C 
    FROM MYTable 
    GROUP BY C
) AS TABLE1 
INNER JOIN
(
SELECT *
FROM MYTable
) AS TABLE2 ON TABLE1.A = TABLE2.A

SQLFIDDLE

您可以通过简单的连接查询来完成。连接查询总是运行得更快然后在查询中。连接查询在执行查询时只运行一次。我们可以使用IN查询归档相同的结果。