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
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
Update 1
The recommended method is the one mentioned by @Zhorov, but i will leave my answer to give all possible solutions
Initial answer
Try using a similar query:
SELECT T.station, T.maxnum, MAX(T.tim) as maxtim
FROM (SELECT station, tim, MAX(num) as maxnum
GROUP BY station, tim ) T
GROUP BY station, maxnum
OR
WITH CTE_1 as (SELECT station, tim, MAX(num) as maxnum
GROUP BY station, tim)
SELECT station, maxnum, Max(tim)
FROM CTE
GROUP BY station, tim
You could use the ROW_NUMBER
partition function, something along these lines should do the trick:
SELECT [Station], [Num], [Tim]
FROM
(
SELECT Station,
Num,
Tim,
ROW_NUMBER() OVER(PARTITION BY Station ORDER BY Num DESC, Tim DESC) [N]
FROM tst
) SQ
WHERE [N] = 1
This works on the basis of taking each group of rows, as grouped by the Station
column (this is what the PARTITION BY
part of the ROW_NUMBER()
statement refers to), then ordering them first by Num
and then by Tim
and assigning each row in the result set a row number. The outer query then takes only the first row of each group, ie for each value of Station
it takes the one with the highest value for Num
and Tim
.
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.