sql查询选择最近的记录以及空记录

时间:2013-03-26 04:12:03

标签: sql-server-2008

我有2个表..我正在将状态历史记录移动到一个表并将其显示在另一个表中...第二个表获取最近的状态并在网页output中显示它

像这样我需要..但是我得到了

needed output

我需要更新的记录以及空状态记录。我的疑问是:

with ctr as
(
 select en.status update,ed.no,row_number()
 over (partition by ed.no order by en.update descending) as [RN], 
 ed.[conference date],ed.conference name,ed.region,ed.inquiry,
 ed.attended by,ed.doctor name,ed.hospital,ed.contact no,ed.email, ed.adds,
 CONVERT(VAR CHAR(10),en.[update], 103) as update,ed.closed,
 CONVERT(VAR CHAR(10),ed.[closing date],103) as closing date,
 ed.closed by, ed.revenue, ed.approve status, ed.Enid from inquiries_details ed
 inner join
 inquiries en on ed.Enid = en.Enid
 inner join
 staff_details SD on ed.region = SD.state
 where region = 'Maharashtra' 
)
 select * from ctr where RN = 1 

任何人都可以帮助我

1 个答案:

答案 0 :(得分:0)

您可以尝试下面的查询,可能是内部联接的问题..将其更改为左联接

with ctr as
(
 select en.status update,ed.no,row_number()
 over (partition by ed.no order by en.update descending) as [RN], 
 ed.[conference date],ed.conference name,ed.region,ed.inquiry,
 ed.attended by,ed.doctor name,ed.hospital,ed.contact no,ed.email, ed.adds,
 CONVERT(VAR CHAR(10),en.[update], 103) as update,ed.closed,
 CONVERT(VAR CHAR(10),ed.[closing date],103) as closing date,
 ed.closed by, ed.revenue, ed.approve status, ed.Enid from inquiries_details ed
 left join
 inquiries en on ed.Enid = en.Enid
 left join
 staff_details SD on ed.region = SD.state
 where region = 'Maharashtra' 
)
 select * from ctr where RN = 1