Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
tpavan7329
Starting Member
18 Posts |
Posted - 2011-03-08 : 17:41:49
|
I want to combine both the queries below into one select statement without using Temp table and insert them in Table A.First Select gets all the history for a phoneid and its idFor example for a phone ‘19999999999’, if there are two id’s 11494462 and 11494465, second query will pick only max of id record for a phone. declare @startDate datetimedeclare @endDate datetimeset @startDate= getdate() - 1set @endDate= getdate() --select @startdate, @enddate--AFP recordsselect m.phoneid as afp_id,m.destination as afp_destination,mh.id as afp_mhid,mh.statusCode as afp_statusCode,mh.reasoncode as afp_reasonCode,mh.statusText as afp_statusText,mh.aStatusCode as afp_aStatusCode,mh.aReasonCode as afp_aReasonCode,mh.aggregatorStatusText as afp_aStatusText,mh.created as afp_CreationDateinto #temp_afp_all_historyfrom [Mhistory] mh,messagess] m with (nolock)where mh.msgTableId=m.id and responsetype=7 and m.created between @startDate and @endDate--AFP records with most recent messages per idselect afp.* into #temp_afp_allfrom #temp_afp_all_history afpinner join (select afp_phoneid,max(afp_mhid) as afp_mhid from #temp_afp_all_history group by afp_phoneid) afp_laston afp.afp_mhid=afp_last.afp_mhidT Pavan Kumar |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2011-03-08 : 21:05:32
|
[code]; with data as(select m.phoneid as afp_id ,m.destination as afp_destination ,mh.id as afp_mhid ,mh.statusCode as afp_statusCode ,mh.reasoncode as afp_reasonCode ,mh.statusText as afp_statusText ,mh.aStatusCode as afp_aStatusCode ,mh.aReasonCode as afp_aReasonCode ,mh.aggregatorStatusText as afp_aStatusText ,mh.created as afp_CreationDate, row_no = row_number() over (partition by afp_phoneid order by afp_mhid desc)from [Mhistory] mh,messagess] m with (nolock)where mh.msgTableId=m.id and responsetype=7 and m.created between @startDate and @endDate)select *from datawhere row_no = 1[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
|
|
|
|