如何从具有多个重复值的表中获取前N个不同的行?

时间:2016-03-01 11:59:41

标签: sql sql-server

我在Microsoft SQL服务器上有以下表格:

NumContr  SeqYear check
111111111   1   -0.50
111111111   2   -0.30
111111111   3    0.30
111111111   4    0.00
111111111   5   -40.00
111111111   6   -200.00
111111111   7   -100.00
111111111   8   -0.50
111111111   9   -0.30
111111111   10   0.30
111111111   11   0.00
111111111   12  -40.00
111111111   13  -200.00
111111111   14  -100.00
400247129   1    NULL
400247129   2    NULL
400247129   3    NULL
400247129   4    NULL
400247129   5    NULL
400247129   6    NULL
400247129   7    NULL
400247129   8    0.00
400247129   9    15254.05
400247129   10   15254.05
400247129   11   15254.05
400247129   12   0.00
400247129   13   0.00
400247129   14   0.00

我希望每个SeqYears行中排名前7位NumContr。有没有什么可以实现这个结果集?

表名是tb_FinancialPosition

    111111111   8   -0.50
    111111111   9   -0.30
    111111111   10  0.30
    111111111   11  0.00
    111111111   12  -40.00
    111111111   13  -200.00
    111111111   14  -100.00
    400247129   8   0.00
    400247129   9   15254.05
    400247129   10  15254.05
    400247129   11  15254.05
    400247129   12  0.00
    400247129   13  0.00
    400247129   14  0.00

提前致谢!

2 个答案:

答案 0 :(得分:3)

一种方法是使用变量:

SELECT NumContr, SeqYear, `check`
FROM (
  SELECT NumContr, SeqYear, `check`,
         @rn := IF(@num = NumContr, @rn + 1,
                   IF(@num := NumContr, 1, 1)) AS rn
  FROM tb_FinancialPosition
  CROSS JOIN (SELECT @rn := 0, @num := 0) AS vars
  ORDER BY NumContr, SeqYear DESC) AS t
WHERE t.rn <= 7

Demo here

在SQL Server中,它更容易实现,因为你有窗口函数:

SELECT NumContr, SeqYear, [check]
FROM (
   SELECT NumContr, SeqYear, [check],
          ROW_NUMBER() OVER (PARTITION BY NumContr 
                             ORDER BY SeqYear DESC) AS rn
   FROM tb_FinancialPosition) AS t
WHERE t.rn <= 7

答案 1 :(得分:0)

这是另一种方法

    select * from 
    (
      select * from 
      (
       select NumContr,SeqYear,`Check`
       from practise
       where NumContr ='111111111'
       order by SeqYear desc limit 7
      )t1 order by SeqYear asc 
    )table1


    Union all 

   select * from 
    (
      select * from 
     (
      select NumContr,SeqYear,`Check`
      from practise
      where NumContr ='400247129'
      order by SeqYear desc limit 7
     ) t2 order by SeqYear asc
   ) Table2