SQL查询以获取组的前2条记录

时间:2018-09-18 03:54:32

标签: group-by sql-server-2008-r2

我有一个下面的输入表

function handleGeneric(event) {

    var page = this.props.kindOfPage;

    // Introduce dynamic branching in "generic" event handler, like so
    switch(page) {
      case 'foo':{
        this.handleFoo(event)
        break;
      }
      default:{
        this.handleBar(event)
        break;
      }
    }
}

function dynamicInput() {
    var rState = this.props.reduxState;

    // Simplyify your render method in this way, and delegate conditional
    // branching to event handler    
    return <input type="text" placeholder={rState.value} 
                  onChange={ event => this.handleGeneric(event) } />
}

预期产量

Source  EventType
A        X
A        X
A        X
A        Y
A        Y
A        Z
B        L
B        L
B        L
B        L
B        M
B        N
B        N

如何形成一个SQL查询以获取如上所述的结果? 我能够取得结果,但一次只有一个来源。

Source    EventType   Frequency
A          X            3
A          Y            2
B          L            4
B          N            2

1 个答案:

答案 0 :(得分:0)

我们可以在此处使用ROW_NUMBER

WITH cte AS (
    SELECT Source, EventType, COUNT(*) as Frequency,
        ROW_NUMBER() OVER (PARTITION BY Source ORDER BY COUNT(*) DESC) rn
    FROM myEventTable
    GROUP BY Source, Eventtype
)

SELECT Source, EventType, Frequency
FROM cte
WHERE rn <= 2;

enter image description here

Demo

之所以可行,是因为ROW_NUMBER操作完成后,即在组中运行GROUP BY。然后,我们可以按频率降序轻松地将每个源的前2个限制在前。