如何 select 最多两列并按车站分组

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

我有一个简单的table像这样

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

想要的输出是这样的

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

我写了这段代码,但是对于 station=1 和 num=200 return 两行

(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 

更新 1

推荐的方法是@Zhorov提到的方法,但是我会留下我的答案来给出所有可能的解决方案


初步回答

尝试使用类似的查询:

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

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

一种可能的方法是使用 ROW_NUMBER() 对按 station 分组并按 numtim 降序排序的行进行编号,然后 select 行数字等于 1.

输入:

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)

声明:

;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

输出:

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

您可以使用 ROW_NUMBER 分区函数,按照这些行应该可以解决问题:

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

这是在获取每组行的基础上工作的,这些行按 Station 列分组(这是 ROW_NUMBER() 语句的 PARTITION BY 部分所指的内容),然后先按 Num 对它们进行排序,然后按 Tim 对它们进行排序,并为结果集中的每一行分配一个行号。然后,外部查询仅采用每个组的第一行,即对于 Station 的每个值,它采用 NumTim.

的最高值。