如何同时选择最大和第二个最大值sql?

时间:2018-08-03 15:29:54

标签: sql sql-server max

table

请参考上图。我需要为每个唯一的ID选择windows_files<tbody> <tr ng-repeat="country in countries"> <td ng-repeat="name in country.countriesName.split(',')"> {{ name }} </td> </tr> </tbody> ,相应的价格,IDMAX(SCHEDULE_DATE)),相应的价格。因此输出将如下所示:

capture2

当前,我编写的查询返回每个ID的两个记录,并且两个记录中的MAX_DATE相同。

Second_MAX

5 个答案:

答案 0 :(得分:3)

我将使用row_number()函数进行条件聚合:

select id, 
       max(case when seq = 1 then schedule_date end) as max_schedule_date,
       max(case when seq = 1 then price end) as max_price,
       max(case when seq = 2 then schedule_date end) as second_max_schedule_date,
       max(case when seq = 2 then price end) as second_max_price
from (select *, row_number() over (partition by id order by schedule_date desc) seq
      from table
     ) t
where seq < 3
group by id;

答案 1 :(得分:0)

我不会将其全部写出来,但这应该可以给您一个想法。

WITH id_rn AS 
  (  SELECT ID,
            ROW_NUMBER() OVER 
            ( PARTITION BY id 
                   ORDER BY schedule_date DESC
            ) rn
        FROM T_Table1
  )

  SELECT DISTINCT
         T1.id
         id_rn1.rn AS MAX_RN,
         id_rn2.rn AS SEC_RN
    FROM T_Table1 T1
   INNER
    JOIN id_rn 
      ON T1.id = id_rn.id
     AND id_rn.rn = 1
   INNER
    JOIN id_rn2 
      ON T1.id = id_rn2.id
     AND id_rn2.rn = 2;

答案 2 :(得分:0)

sub-queryrow_number()功能一起使用

select id, 
       max(case when rn= 1 then schedule_date end) as max_schedule_date,
       max(case when rn= 1 then price end) as max_price,
       max(case when rn= 2 then schedule_date end) as second_max_schedule_date,
       max(case when rn = 2 then price end) as second_max_price from    
    (select t.*, row_number() over (partition by id order by Price desc) rn
          from yourtable t
    ) as Tsub where Tsub.rn in (1,2)
 group by id

答案 3 :(得分:0)

backend      : macosx

答案 4 :(得分:0)

WITH a
     AS (
     SELECT ROW_NUMBER() OVER(PARTITION BY ID ORDER BY SCHEDULE_DATE DESC) RN,
            ID,SCHEDULE_DATE,PRICE
     FROM T_Table1)
     SELECT * FROM a a1 LEFT JOIN A a2 ON a1.ID = a2.ID AND a2.rn = 2
     WHERE a1.rn = 1;

SQLFiddle