获取每组两列的前n行

时间:2016-12-16 20:54:00

标签: sql sql-server sql-server-2008

这个问题与Get top 1 row of each group不同。在我的问题中,每个组由两列(col1,col2)组成,而在他的问题中,每个组只包含一列(col1)。我也尝试在他的问题中修改答案,但失败了。

Example:

Suppose n = 1

Input:
col1 col2 x Amt
A     B   x1 100
A     B   x2 200
C     D   x3 400
C     D   x4 500
...more data ...

Output:
col1 col2 x Amt
A     B   x2 200
C     D   x4 500
...more data ...

我尝试了...select *, row_numne() over ( partition by (col1, col2) order by ...

4 个答案:

答案 0 :(得分:1)

您仍然可以在row_number内使用CTE。我们的想法是根据您的分组获取所有行,即< =您传入的数字。这类似于根据AMT的顺序获取配对的前n行

declare @count int = 1
with cte as(
    select 
        col1,
        col2,
        x,
        Amt,
        row_number() over (partition by col1, col2 order by Amt desc) as rn
    from yourTable)

select 
    col1,
    col2,
    x,
    Amt
from cte
where rn <= @count

答案 1 :(得分:1)

Declare @Top int = 1

Select col1,col2,x,Amt 
 From  (
         Select *
               ,RN=Row_Number() over (Partition By Col1,Col2 Order By Amt Desc) 
         From  YourTable ) A
 Where RN<=@Top

返回

col1    col2    x   Amt
A       B       x2  200
C       D       x4  500

答案 2 :(得分:0)

为什么简单的max不适合你?

select col1, col2, max(x), Max(Amt) from yourtable
  group by col1, col2

答案 3 :(得分:0)

这是CROSS APPLY选项,带有测试表以确认其功能:

DECLARE @MyTable TABLE (Col1 varchar(4) not null, Col2 varchar(4) not null, x varchar(8) not null, amt int not null)

INSERT INTO @myTable VAlues ('A', 'B', 'x1', 100)
INSERT INTO @myTable VAlues ('A', 'B', 'x2', 200)
INSERT INTO @myTable VAlues ('C', 'D', 'x4', 400)
INSERT INTO @myTable VAlues ('C', 'D', 'x3', 500)


DECLARE @n int
SET @n = 1

SELECT DISTINCT 
    m.Col1,
    m.Col2,
    m2.x,
    m2.Amt
FROM @MyTable m
CROSS APPLY (
    SELECT TOP(@n) Amt, x
    FROM @MyTable 
    WHERE col1 = m.Col1
        AND col2 = m.col2
    ORDER BY Amt Desc, x Desc
    ) m2