TSQL - 获取其标题不为空的最新行

时间:2017-01-17 08:39:53

标签: tsql

我有以下表格:

========================
Id     SubCode    Title
========================
 1        1       test1
 1        2       test2
 1        3       NULL
 1        4       NULL
 2        1        k1
 2        2        k2
 2        3        k3
 2        4       NULL

不,我想选择标题不是null的最新行,例如标识为1,然后查询必须显示test2,而ID {1}}必须是2

k3

我写了这个查询:

========================
Id     SubCode    Title
========================
 1        2       test2
 2        3        k3

但是这段代码给出了错误的结果:

select t.Id, t.SubCode, t.Title from Test t
inner join (
    select max(Id) as Id, max(SubCode) as SubCode
    from Test
    group by Id
) tm on t.Id = tm.Id and t.SubCode = tm.SubCode

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

你需要在内部选择中使用Title is not null where子句:

select t.Id, t.SubCode, t.Title from Test t
inner join (
    select max(Id) as Id, max(SubCode) as SubCode
    from Test
    where Title is not null
    group by Id
) tm on t.Id = tm.Id and t.SubCode = tm.SubCode

答案 1 :(得分:2)

您忘记通过编写适当的WHERE子句(where title is not null)来排除 NULL。

然而,这些问题(获得最佳/最后/ ......记录)通常最好通过分析函数(RANKDENSE_RANKROW_NUMBER)解决,因为有了它们你只访问一次表:

select id, subcode, title
from
(
  select id, subcode, title, rank() over (partition by id order by subcode desc) as rn
  from test
  where title is not null
) ranked
where rn = 1;