简体   繁体   English

非唯一 id 的最后一个条目,其中 X=Y

[英]Last entry for non-unique id where X=Y

预期数据

Please see the above image for rows I would like returned, those highlighted in yellow.请参阅上图了解我想要返回的行,这些行以黄色突出显示。

From the picture attached, I would like it to only return id 133766 and 133792 as they end at stage 5 .从附图中,我希望它只返回 id 133766133792 ,因为它们在第 5 阶段结束。

I want to pull the last entry for a non-unique id where there could be X amount of entries per non-unique id.我想为非唯一 id 提取最后一个条目,其中每个非唯一 id 可能有 X 个条目。

I am not overly experience in SQL, but what I know is;我在 SQL 方面并没有过多的经验,但我所知道的是;

I could do我可以

SELECT max(stage), id
FROM [dbo].[table] group by id

and this gives me a pretty good starting point.这给了我一个很好的起点。 I'd rather sort on the date field, as the "stage" isn't actually an int, I've done that for simplicity here.我宁愿在日期字段上排序,因为“舞台”实际上不是一个整数,为了简单起见,我在这里做了。

So I essentially need to get the last entry (figured out by date) for all non-unique id's where stage doesn't equal X所以我基本上需要获取所有非唯一 id 的最后一个条目(按日期计算),其中 stage 不等于 X

I feel like it's a really simple, everyday query, but I just can not wrap my head around a simple, efficient way to do it.我觉得这是一个非常简单的日常查询,但我无法用一种简单、有效的方法来完成它。

Any help is much appreciated.任何帮助深表感谢。

try this尝试这个

SELECT * 
FROM(
SELECT Id, Stage, CompletionDate
    ,Row_number() OVER(PARTITION BY ID ORDER BY CompletionDate DESC) AS RN
FROM YourTable
) AS t
WHERE RN = 1 AND Stage = 5;

You could use the window version of MAX您可以使用MAX的窗口版本

;WITH CTE_DATA AS
(
  SELECT *
  , MAX(stage) OVER (PARTITION BY id) AS max_stage
  FROM [dbo].[table]
)
SELECT *
FROM CTE_DATA
WHERE stage = max_stage
  AND max_stage = 5;

I want to point out that not exists is also a way to approach this:我想指出not exists也是解决这个问题的一种方法:

select t.*
from t
where t.stage = 5 and
      not exists (select 1
                  from t t2
                  where t2.id = t.id and t2.stage > t.stage
                 );

With an index on (id, stage) , you might be surprised at how good the performance is.使用(id, stage)上的索引,您可能会对性能如此之好感到惊讶。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM