Select 列中具有唯一值的行,按时间戳排序?

Select rows with unique value in a column, ordered by Timestamp?

我需要 select RelationShipId 的 3 个最近的唯一行(因此没有重复行)以及选择的时间戳最接近今天的行。

我有一个现在看起来像这样的查询,但它不起作用。

我得到一个:在 select 列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

我目前拥有的脚本:

SELECT * FROM PlayerAction
WHERE [ActionType] = 'SomeString' AND [RelationShipType] = 'SomeString' AND [PlayerId] = 5 AND [Deleted] = 0
GROUP BY RelationShipId
ORDER BY [TimeStamp] DESC
OFFSET 1 ROWS
FETCH NEXT 3 ROWS ONLY

样本数据

{
 PlayerId=5
 ActionType="SomeString"
 RelationShipType="SomeString"
 RelationShipId=1
 TimeStamp=2019-07-04 07:45:47.400
 Deleted=0
}
{
 PlayerId=5
 ActionType="SomeString"
 RelationShipType="SomeString"
 RelationShipId=2
 TimeStamp=2019-07-03 14:29:10.530
 Deleted=0
}
{
 PlayerId=5
 ActionType="SomeString"
 RelationShipType="SomeString"
 RelationShipId=3
 TimeStamp=2019-07-03 13:56:26.057
 Deleted=0
}

假设有 5 行具有相同的 RelationShipId,无穷无尽的 RelationShipId。我想要 TimeStamp 的前 3 个唯一行,最后三个 PlayerActions

看来你需要 distinct 和 top

SELECT distinct top 3 * FROM PlayerAction
        WHERE [ActionType] = 'SomeString' AND [RelationShipType] = 'SomeString' AND [PlayerId] = SomeNumber AND [Deleted] = 0
       ORDER BY [TimeStamp] DESC