如何选择最后一个存在某个值的行,但如果介于两者之间则不行

时间:2018-07-20 05:58:01

标签: sql-server tsql

我有这张桌子。使用case#,Linenumber和code#。

case#   Linenumber  Code#
99L1HV  1           1510
99L1HV  2           4320
99PX58  1           1510
99PX58  2           4320
99PX58  3           4500
99PX59  1           1510
99PX59  2           918
99PX59  3           4320

如何获取每个案例的最后一个LineNumber的记录#代码= 4320

输出应该是这样

case#   Linenumber  Code
99L1HV  2           4320
99PX59  3           4320

4 个答案:

答案 0 :(得分:1)

使用ROW_NUMBER获得的数字与每种情况下的行号相反。#
然后最后一行的RN = 1

SELECT [case#], Linenumber, [Code#]
FROM
(
    SELECT [case#], Linenumber, [Code#],
     ROW_NUMBER() OVER (PARTITION BY [case#] ORDER BY Linenumber DESC) AS RN
    FROM yourtable
) q
WHERE RN = 1 
  AND [Code#] = 4320
ORDER BY [case#];

或更简洁的版本。
将TOP 1 WITH TIES与ORDER BY ROW_NUMBER结合使用。

SELECT * 
FROM
(
    SELECT TOP 1 WITH TIES [case#], Linenumber, [Code#]
    FROM yourtable
    ORDER BY ROW_NUMBER() OVER (PARTITION BY [case#] ORDER BY Linenumber DESC)
) q
WHERE [Code#] = 4320
ORDER BY [case#];

答案 1 :(得分:0)

with cte as 
(select case#, max(linenumber)
from source_table 
group by case#)
select t1.*
from source_table t1 inner join cte t2
on t1.case# = t2.case# and t1.linenumber = t2.linenumber
where t1.Code# = 4320

答案 2 :(得分:0)

cte将通过case#生成运行编号。 rn = 1将是每种情况的最后一行#

; with cte as
(
    select *, rn = row_number() over (partition by [case#] order by linenumber desc)
    from   yourtable
)
select *
from   cte
where  rn     = 1 
and   [code#] = 4320

答案 3 :(得分:0)

declare @t table (
    CaseNumber varchar(10),
    LineNumber int,
    CodeNumber int
);

-- Filling the table with data, skipped

select t.*
from @t t
where t.CodeNumber = 4320
    and not exists (
        select 0 from @t x
        where x.CaseNumber = t.CaseNumber
            and x.LineNumber > t.LineNumber
    );