我目前有此查询返回表格中的最新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
函数的上限,或者是否有更好的函数可供使用,以便我可以为此函数添加“小于(日期)”子句?
我不想向AND DerivedTable.MostRecentChange <= '2016-12-30 23:59:59'
添加INNER JOIN
之类的内容,因为这不是我正在寻找的解决方案。
答案 0 :(得分:3)
MAX(case when DateUpdated <= '2016-12-30 23:59:59' then DateUpdated end)
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
X 10
总执行时间103977毫秒
select max(case when dt <= '2016-01-01 00:00:00' then dt end) from #t
X 10
总执行时间118738毫秒
10 X 100M rows: 14.761 sec Average difference per 100M rows: 1.476 sec Average difference per 1M rows: 0.015 sec
答案 1 :(得分:0)
T-SQL MAX()函数支持Partition By子句,就像Count,Sum或Row_Number函数一样。
您可以在示例SQL系统视图
上使用MAX(),如下所示select distinct
object_id,
max(column_id) over (partition by object_id)
from sys.columns
也许你可以在Partition By字段的位置使用函数结果或字段来获得所需的输出