每条记录都包含RecordID, TypeID, GroupID
Type
有很多记录,Group
有很多类型的记录
我想为每种类型和组合返回3条记录。
有什么建议吗?
这样的简化输出
Group | Type | Record
------+------+--------
1 | 1 | 1
1 | 1 | 2
1 | 1 | 3
1 | 2 | 1
1 | 2 | 2
1 | 2 | 3
1 | 3 | 1
....
9 | 1 | 1
9 | 2 | 2
etc..
这是对我有用的解决方案,是给出答案的一种变体。
它是迁移的代码,因此绝对优化不是必需的 - 但需要进一步了解。
SELECT *
FROM yourTable t1
WHERE EXISTS
(SELECT RecordId
FROM (
SELECT RecordId, ROW_NUMBER() OVER (PARTITION BY GroupId, TypeId ORDER BY RecordId) As seq FROM yourTable) t2
WHERE seq <= 3 AND t2.RecordId = t1.RecordId
)
ORDER BY GroupId, TypeId
答案 0 :(得分:1)
尝试这样的事情:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupId, TypeId ORDER BY RecordId) As seq
FROM yourTable) dt
WHERE seq <= 3