TSQL-获取标题不为空的最新行
我有以下表格:TSQL-获取标题不为空的最新行,tsql,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
========================
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
的最新行,例如对于Id1
,则查询必须显示test2
,对于Id2
,它必须是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
但该代码给出了错误的结果:
========================
Id SubCode Title
========================
1 4 NULL
2 4 NULL
有什么想法吗?您需要一个
标题不为空的where子句,在您的内部select中:
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
您需要在内部select中有一个标题为NOTNULL的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
您忘记了通过编写适当的WHERE
子句(WHERE title not null
)来排除null
然而,这些问题(为了获得最佳/最后一条/…记录)通常最好通过分析函数(RANK
,densite\u RANK
,ROW\u 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;
您忘记了通过编写适当的WHERE
子句(WHERE title not null
)来排除null
然而,这些问题(为了获得最佳/最后一条/…记录)通常最好通过分析函数(RANK
,densite\u RANK
,ROW\u 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;
所以SubCode
决定了一条记录有多旧?我没有问过键,我问过你是如何决定哪条记录“旧”的,因为你“想选择最新的行”?您应该使用datetime
-column-@sirwanafi。表中插入行的顺序不能保证是查询返回行的顺序。所有查询都被认为是无序的,除非指定了
Order by
。@Sirwan Afifi:表中没有插入顺序。根据定义,表数据是无序的。如果没有列指示最新插入的记录(时间戳或序列),则无法访问该记录。因此,最新记录在表中具有最大子代码只是巧合?它们也可以有最小的子代码或任何其他代码?那么你就没有办法访问最新的记录了。好吧,那么,我已经取消删除了我的答案,因为这句话恰好是正确的:-)那么SubCode
决定了一条记录有多旧?我没有要求提供键,我问过你如何确定哪条记录“旧”,因为你“想选择最新的行”?您应该使用datetime
-column-@sirwanafi。表中插入行的顺序不能保证是查询返回行的顺序。所有查询都被认为是无序的,除非指定了
Order by。@Sirwan Afifi:表中没有插入顺序。根据定义,表数据是无序的。如果没有列指示最新插入的记录(时间戳或序列),则无法访问该记录。因此,最新记录在表中具有最大子代码只是巧合?它们也可以有最小的子代码或任何其他代码?那么,你没有办法访问最新的记录。好吧,我已经删除了我的答案,因为这个声明正好是正确的:-我不知道为什么我没有考虑<代码>哪里的条款< /代码>:]顺便说一下,我不知道为什么我没有考虑<代码>哪里条款< /代码>:)