Over(Partition)SQL - 没有结果

时间:2014-05-28 21:02:51

标签: 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: 628678,文字:所有捐赠者都会收到免费T恤,两张即兴票和泽西迈克的子优惠券! NoteID:< / strong> 1410233

DriveID :628678,文字:所有捐赠者都会收到免费T恤,两张即兴票和泽西迈克的子优惠券! NoteID: 1410234

但是当我尝试使用over(分区)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)

返回没有结果。关于我在这里缺少什么的任何建议?

2 个答案:

答案 0 :(得分:0)

我认为你正在努力做到这一点。看看你是否更喜欢这种方式,它还可以让你更好地找到问题。我想这可能是因为你没有在你的subselect中包含“和noteid = ...”max(createdate)。

(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
)

答案 1 :(得分:0)

根据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)