检索SQL中的最新活动

时间:2018-02-28 08:13:52

标签: sql sql-server database

美好的一天

我有一个在不同日期发生的活动表,可以通过查询(T-SQL)检索:

Select  Activities.activityid,
        Activities.ActivityTypeCode,
        Activities.ActivityDate,
        Activities.SequenceOrder,
        Activities.Place,
        Activities.TypeOfPlace
From Activities
Where Activities.ActivityTypeCode In ('LOST', 'FOUND', 'NOT SEEN')

奎斯顿:我如何找回最新的?还是第二个最近的?

您的信息:有一个名为sequenceOrder的字段,用于跟踪输入活动时的顺序。

请帮忙。

3 个答案:

答案 0 :(得分:2)

GROUP BY子句与子查询

一起使用
SELECT * 
FROM Activities
WHERE sequenceOrder IN (
              SELECT MAX(SequenceOrder) 
              FROM Activities
              WHERE ActivityTypeCode In ('LOST', 'FOUND', 'NOT SEEN')
              GROUP BY ActivityTypeCode 
)

如果您希望获得( LOST FOUND NOT SEEN)之一中唯一最活跃的活动,请删除{{ 子查询中的1}}子句。

答案 1 :(得分:0)

使用ROW_NUMBER

SELECT
    activityid,
    ActivityTypeCode,
    ActivityDate,
    SequenceOrder,
    Place,
    TypeOfPlace
FROM
(
    SELECT *,
        ROW_NUMBER() OVER (ORDER BY SequenceOrder DESC) rn
    FROM Activities
    WHERE ActivityTypeCode IN ('LOST', 'FOUND', 'NOT SEEN')
) t
WHERE rn = 1;

这种方法的优点是,如果您想要第二个最近的事件,我们可以使用WHERE rn = 2

请注意,如果序列顺序中的值可能存在关联,那么我们可能希望使用排名函数而不是行号。

您可以将上述查询放入CTE(公用表表达式):

WITH cte AS (
    SELECT
        activityid,
        ActivityTypeCode,
        ActivityDate,
        SequenceOrder,
        Place,
        TypeOfPlace
    FROM
    (
        SELECT *,
            ROW_NUMBER() OVER (ORDER BY SequenceOrder DESC) rn
        FROM Activities
        WHERE ActivityTypeCode IN ('LOST', 'FOUND', 'NOT SEEN')
    ) t
    WHERE rn = 1
)

SELECT * FROM cte;

但请注意,从性能的角度来看,在子查询中包装查询是不可取的。相反,只需定制我的原始查询以满足您的需求。

答案 2 :(得分:0)

select * from (
Select  Activities.activityid,
    Activities.ActivityTypeCode,
    Activities.ActivityDate,
    Activities.SequenceOrder,
    Activities.Place,
    Activities.TypeOfPlace,
    row_number() over (partition by Activities.ActivityTypeCode order by Activities.SequenceOrder) [rn]
From Activities
Where Activities.ActivityTypeCode In ('LOST', 'FOUND', 'NOT SEEN')
) a where rn = 1 --2 if you want second most recent