获取最大值(日期),最大日期不应该是当前日期

时间:2016-08-30 05:16:31

标签: sql sql-server

我是这个领域的新手。请帮助我。我有一个表和一个日期列,我想根据最新日期获得记录。所以我使用了max(date),但后来我意识到max(date)不应该是今天的日期。任何sql服务器的帮助将不胜感激。

declare @comp1 bigint
set @comp1=(select isnull((select sum(completed_count) as a from table1 where JOBID=580 and status<>'I' and targetdate=(select max(targetdate) from table1 where status<>'I' and id=580)),0) )
declare @bal1 bigint
set @bal1=(select isnull((select TotalVol from table2 where TargetDt=(select max(TargetDt) from table2 where status<>'I' and id=580) and Id=580 and Status<>'I'),0))
declare @pend1 bigint
set @pend1=(select isnull((select count(id) as c from table3  where status='p' and MOD_PROJ_ID=171 and id=580 and 
UPDATED_DT=(select max(UPDATED_DT) from table3 where status='p' and id=580) group by id),0))
select @bal1-@comp1+@pend1 as answer

抱歉,我也是stackoverflow的新手。请帮忙

1 个答案:

答案 0 :(得分:1)

根据我在评论中的内容,您需要通过

扩展您的where子句
UPDATED_DT < CAST(SYSDATETIME() AS date))

选择最长日期时:

UPDATED_DT=(select max(UPDATED_DT) from table3 where status='p' and id=580 AND UPDATED_DT < CAST(SYSDATETIME() AS date)) group by id),0))