Skip to content
Advertisement

how to select max of two columns and group it by station

I have a simple table like this

 station    num     tim
   1        150    10
   1       200     222
   1       100     5000
   1       200     555
   2       100     500
   2       120     200
   3        1      2

The output desired is like this

station num     tim
   1    200     555
   2    120     200
   3    1       2

i wrote this code but for station=1 and num=200 return two rows

(SELECT a.station , a.num ,a.tim
FROM test.dbo.tst a
JOIN (
SELECT station, MAX(num) num
FROM test.dbo.tst
GROUP BY station
) b ON a.station = b.station and a.num=b.num ) order by station 

Advertisement

Answer

One possible approach is to use ROW_NUMBER() to number rows grouped by station and ordered by num and tim descending and then select the rows with number equal to 1.

Input:

CREATE TABLE #Stations (
   station int,
   num int,
   tim int
)
INSERT INTO #Stations
   (station, num, tim)
VALUES
   (1, 150, 10),
   (1, 200, 222),
   (1, 100, 5000),
   (1, 200, 555),
   (2, 100, 500),
   (2, 120, 200),
   (3, 1,   2)

Statement:

;WITH cte AS (   
   SELECT 
      station, 
      num, 
      tim,
      ROW_NUMBER() OVER (PARTITION BY station ORDER BY num DESC, tim DESC) AS Rn
   FROM #Stations
)
SELECT 
   station, 
   num, 
   tim
FROM cte
WHERE Rn = 1

Output:

station num tim
1       200 555
2       120 200
3       1   2
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement