Author |
Topic |
xpandre
Posting Yak Master
212 Posts |
Posted - 2015-01-26 : 22:58:19
|
sql server : 2008create table a (id int, status varchar(100), created_date datetime)goinsert into a(id, status, created_date)select 1,'post',getdate()union allselect 1,'confirm',dateadd(mi,1,getdate())union allselect 1,'error',dateadd(mi,2,getdate())union allselect 1,'resend',dateadd(mi,3,getdate())union allselect 2,'post',getdate()union allselect 2,'confirm',dateadd(mi,4,getdate())union allselect 2,'error',dateadd(mi,5,getdate())select * from aoutput I want is:for ID 1, I have a status of error, and after that it was resend..so this should not be returned.for ID 2, I have a status of error, and after that it was not resend..so this should be returned.The SP input is nothing. We always need to check for the error status and if any other message was posted after error. If yes, then ignore it, else return it.I tried doing getting all id's with "error" status into a temp tablethen partition it with row_number order by create dateand if row number = 1 and status = error, return else do not returnBut this solution would not be good enough when the data grows:-( |
|
AASC
Starting Member
24 Posts |
Posted - 2015-01-27 : 02:56:51
|
You do not need to create and dump data into Temp table, use derived table instead.Also create a NonClustered index on table and apply DESC sort on created_date. CREATE NONCLUSTERED INDEX [IX_ID_CreatedDate] ON [dbo].[a] ( [id] ASC, [created_date] DESC)INCLUDE ( [status]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]GOselect * from(select row_number()over(partition by id order by id,created_date desc) RID,* from a Outa)a where RID=1 and status='error' |
|
|
|
|
|