Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
T-SQL最大函数替换_Sql_Sql Server_Tsql - Fatal编程技术网

T-SQL最大函数替换

T-SQL最大函数替换,sql,sql-server,tsql,Sql,Sql Server,Tsql,我当前有一个查询,返回表中最近的ID: SELECT StatusUpdates.ForeignId, StatusUpdates.DateUpdated AS MostRecentChange FROM hjStatusUpdates StatusUpdates INNER JOIN ( SELECT ForeignId, MAX(DateUpdated) AS MostRecentChange FROM hjStatusUpdates GROUP BY For

我当前有一个查询,返回表中最近的ID:

SELECT StatusUpdates.ForeignId,
StatusUpdates.DateUpdated AS MostRecentChange
FROM hjStatusUpdates StatusUpdates
INNER JOIN (
    SELECT ForeignId,
    MAX(DateUpdated) AS MostRecentChange
    FROM hjStatusUpdates
    GROUP BY ForeignId) DerivedTable
    ON StatusUpdates.ForeignId = DerivedTable.ForeignId
    AND StatusUpdates.DateUpdated = DerivedTable.MostRecentChange
WHERE StatusUpdates.ForeignTable = 'hjClientAccounts';
我的问题是,是否可以设置
MAX
函数的上限,或者是否有更好的函数可供使用,以便我可以向该函数添加“小于(日期)”子句

我不想添加类似于
和DerivedTable.MostRecentChangeT-SQL MAX()的函数,它支持按子句划分,就像Count、Sum或Row_Number函数一样

可以在示例SQL系统视图上使用MAX(),如下所示

select distinct 
object_id, 
max(column_id) over (partition by object_id) 
from sys.columns
也许您可以使用函数结果或字段来代替按字段划分来获得所需的输出

MAX(case when DateUpdated <=  '2016-12-30 23:59:59' then DateUpdated end) 
x10

总执行时间103977毫秒


评论不用于扩展讨论;这段对话已经结束。
with t(n) as (select 0 union all select n+1 from t where n<9)
select      getdate() - RAND(cast(NEWID() as varbinary))*365*10  as dt 
into        #t 
from        t t0,t t1,t t2,t t3,t t4,t t5,t t6,t t7
select max(dt) from #t
select max(case when dt <= '2016-01-01 00:00:00' then dt end) from #t
10 X 100M rows:                    14.761 sec
Average difference per 100M rows:   1.476 sec
Average difference per 1M rows:     0.015 sec