SQL Server 2014 - select 语句有两个条件
SQL Server 2014 - select statements with two contitions
事情是这样的:我有一个 table,其中有一列用于路径,另一列用于日期。由于我是这个 SQL 世界的新手,所以我不确定哪种说法更适合这个问题。它必须给我:
- 如果日期为空,路径列的值或;
- 如果日期不为空,则路径列的值在其日期列中具有最新日期值。
重要的是要注意最后 table 不能有任何重复的路径。
table 现在的样子示例:
path1 |----------------------------|
path2 |----------------------------|
path3 |2020-06-04 00:00:00|
path3 |2020-06-03 00:00:00|
path3 |----------------------------|
现在我有一些查询可以部分解决问题,这里是:
select path_column, date_column
from my_table a
where a.date_column = (select max(date_column)
from my_table b
where a.path_column = b.path_column)
or date_column IS NULL
以上查询结果:
path1 |----------------------------|
path2 |----------------------------|
path3 |2020-06-04 00:00:00|
path3 |----------------------------|
虽然我需要它看起来像这样:
path1 |----------------------------|
path2 |----------------------------|
path3 |2020-06-04 00:00:00|
我的组织目前正在使用 SQL Server 2014。祝你有美好的一天!
使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by path1 order by date desc) as seqnum
from my_table t
) t
where seqnum = 1;
NULL
s 被认为是最低值,因此降序排序将它们放在最后。
你可以使用Group By
子句:-
select path_column, max(date_column) date_column
from my_table group by path_column;
有关演示数据,请访问 This Link
事情是这样的:我有一个 table,其中有一列用于路径,另一列用于日期。由于我是这个 SQL 世界的新手,所以我不确定哪种说法更适合这个问题。它必须给我:
- 如果日期为空,路径列的值或;
- 如果日期不为空,则路径列的值在其日期列中具有最新日期值。
重要的是要注意最后 table 不能有任何重复的路径。
table 现在的样子示例:
path1 |----------------------------|
path2 |----------------------------|
path3 |2020-06-04 00:00:00|
path3 |2020-06-03 00:00:00|
path3 |----------------------------|
现在我有一些查询可以部分解决问题,这里是:
select path_column, date_column
from my_table a
where a.date_column = (select max(date_column)
from my_table b
where a.path_column = b.path_column)
or date_column IS NULL
以上查询结果:
path1 |----------------------------|
path2 |----------------------------|
path3 |2020-06-04 00:00:00|
path3 |----------------------------|
虽然我需要它看起来像这样:
path1 |----------------------------|
path2 |----------------------------|
path3 |2020-06-04 00:00:00|
我的组织目前正在使用 SQL Server 2014。祝你有美好的一天!
使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by path1 order by date desc) as seqnum
from my_table t
) t
where seqnum = 1;
NULL
s 被认为是最低值,因此降序排序将它们放在最后。
你可以使用Group By
子句:-
select path_column, max(date_column) date_column
from my_table group by path_column;
有关演示数据,请访问 This Link