超过(分区)SQL-无结果

超过(分区)SQL-无结果,sql,tsql,window-functions,Sql,Tsql,Window Functions,我试图使用over partition子句来选择一条记录,该记录选择具有max noteid的记录 首先,当我运行此查询时,我会得到预期的结果,返回两条记录: select driveid, text, noteid from rpt_notesdetail where driveid='628678' and Reason in (select codeid from rpt_QuickCodes where DescShort like N'Publicity') 我得到 DriveID:

我试图使用over partition子句来选择一条记录,该记录选择具有max noteid的记录

首先,当我运行此查询时,我会得到预期的结果,返回两条记录:

select driveid, text, noteid from rpt_notesdetail where driveid='628678'
and Reason in (select codeid from rpt_QuickCodes where DescShort like N'Publicity')
我得到 DriveID:628678,文本:所有捐赠者将获得一件免费T恤、两张即兴演奏票和Jersey Mike的次级优惠券!,注:1410233

DriveID:628678,文本:所有捐赠者将获得一件免费T恤、两张即兴演奏票和Jersey Mike的次级优惠券!,注:1410234

但当我尝试使用过分区SQL时:

(select text from (select (Text), noteid, max(noteid) over (partition by driveid) as 'max_note'
from rpt_NotesDetail 
where DriveID='628678' 
and createdate = (select max(createdate) from rpt_notesdetail where DriveID='628678') 
and Reason in (select codeid from rpt_QuickCodes where DescShort like N'Publicity')) AS A where A.noteid = A.max_note)

它不会返回任何结果。关于我在这里遗漏了什么,有什么建议吗?

我想你做得很艰难。看看你是否更喜欢这种方式,它也能让你更好地发现问题。我想这可能是因为你没有包括和noteid=。。。在maxcreatedate的子选择中

(select text from 
(
select (Text), noteid, row_number() over (partition by driveid order by noteid desc) as row_num
from rpt_NotesDetail 
where DriveID='628678' 
and createdate = (select max(createdate) from rpt_notesdetail where DriveID='628678') 
and Reason in (select codeid from rpt_QuickCodes where DescShort like N'Publicity')
) AS A 
-- comment out this line to see all rows, possibly showing the data problem
where A.row_num = 1
)

根据Tim Lehner的建议,我将Reason子查询放在createdate子查询中,它可以工作:

(select text from (select (Text), noteid, max(noteid) over (partition by driveid) as 'max_note'
from rpt_NotesDetail where DriveID="DriveMaster"."DriveID" and createdate =
(select max(createdate) from rpt_notesdetail where
DriveID="DriveMaster"."DriveID" and Reason in
(select codeid from rpt_QuickCodes where DescShort like N'Publicity'))) AS A
where A.noteid = A.max_note)

派生表本身是否返回任何记录?这是括号中的内部查询,别名为?Tim,不,不返回。我注释掉了createdate=select max createdate,我得到了结果。因此,问题似乎来自SQL的这一部分。这些记录的createdate是否可能为null?嘿,Tim,我不相信这个字段可能为null,我知道在这种情况下,它们不是null。max createdate子查询可能应该包括您在派生表中使用的原因,然后。谢谢shriop,不幸的是,如果我在代码中留下和createdate=select max createdate from rpt_notesdetail,我仍然没有得到结果。我不完全确定查询中是否需要和createdate=。嘿,shriop,只要我将原因查询嵌套在create=select maxcreatedate子查询中,您的查询就可以正常工作。