简体   繁体   中英

SELECT Row Values WHERE MAX() is Column Value In GROUP BY Query

How can I select like this? Can I create a User defined Aggregate Function

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

where MyTable as Shown Below

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

I want a Query Like this

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

I'm Expecting the result as below

 MAX(A)  Condition    C
-----------------------
   3        4         S
   6        7         T
 SELECT A,B,C FROM
     (SELECT *, ROW_NUMBER() OVER (PARTITION BY C ORDER BY A DESC) RN FROM MyTable)
 WHERE RN = 1

(this query will always return only one row per C value)

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

(if there are multiple rows that have same Max(A) value - this query will return all of them)

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

update:

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

update 2:

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

update 3:

ok, I think I understand what you're looking for now.. How about this:

SELECT *
FROM MyTable
Where A in (SELECT Max(A) FROM MyTable GROUP BY C) 
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
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

Then try it:

    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

how about this:

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

Try Following Query :

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

you can do it by simple join query . join query always run faster then In query . Join query run only one time at the time of execution of the query . we can archive same result by using IN query .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM