获取组的每个值的最后n次出现

时间:2016-01-14 23:42:36

标签: sql-server

假设我有一个名为tableA的表,其数据为

| col1 | col2 |
| 1    | 5    |
| 1    | 6    |
| 1    | 7    |
| 2    | 1    |
| 2    | 2    |
| 2    | 3    |
| 2    | 4    |
| 3    | 3    |
| 3    | 2    |
| 3    | 1    |

然后我想得到的是col1的每个唯一值的最后两次出现。结果将是

| col1 | col2 |
| 1    | 6    |
| 1    | 7    |
| 2    | 3    |
| 2    | 4    |
| 3    | 2    |
| 3    | 1    |

是否有一个查询可以获得此结果?

2 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER

WITH CTE AS(
    SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col2 DESC)
    FROM tbl
)
SELECT
    col1, col2
FROM CTE
WHERE rn <= 2

答案 1 :(得分:1)

只需扩展Felix的答案,假设有一个ID列:http://www.sqlfiddle.com/#!3/04a5e/3/0

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    yourTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top , animated: true)
}

需要按ID重新排序以保持正确的顺序,再加上在row_number()中按ID排序,因为col2并不总是增量。

相关问题