无需分组/具有/独特

问题描述 投票:0回答:1

我正在尝试找到以下问题的适当解决方案: 我有一个活动跟踪数据库,我想获取特定日期的状态(例如:9 月 11 日)

活动 状态 日期
100 完成 9 月 12 日
100 程序中 9 月 10 日
110 程序中 9 月 12 日
110 程序中 09-9 月
110 08-9 月

我当前的查询是:select * from table where Date <= 11-Sept My current output is:

活动 状态 日期
100 程序中 9 月 10 日
110 程序中 09-9 月
110 08-9 月

问题是我想将每个活动代码限制为仅 1 行(最新日期)。 期望的输出是:

活动 状态 日期
100 程序中 9 月 10 日
110 程序中 09-9 月

但是...

我无法使用group by、having或distinct,因此以下解决方案不可接受:

select distinct Name
from table
where Date <= 11-Sept

select name, max(date)
from table 
where Date <= 11-Sept
group by name

基本上..我只能使用where子句

有人有想法吗?

期望的输出是:

活动 状态 日期
100 程序中 9 月 10 日
110 程序中 09-9 月
sql sql-server where-clause distinct
1个回答
0
投票

执行此操作的一种规范方法是使用

ROW_NUMBER()
窗口函数:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Activity ORDER BY Date DESC) rn
    FROM yourTable
    WHERE Date < '20230911'
)

SELECT Activity, Status, Date
FROM cte
WHERE rn = 1
ORDER BY Activity;
© www.soinside.com 2019 - 2024. All rights reserved.