How do I get the earlist DateTime of a set, where there is a few conditions

Posted by radbyx on Stack Overflow See other posts from Stack Overflow or by radbyx
Published on 2010-05-29T10:49:02Z Indexed on 2010/05/29 10:52 UTC
Read the original article Hit count: 164

Filed under:

Create script for Product

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Product](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[ProductName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED 
(
[ProductID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Create script for StateLog

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[StateLog](
[StateLogID] [int] IDENTITY(1,1) NOT NULL,
[ProductID] [int] NOT NULL,
[Status] [bit] NOT NULL,
[TimeStamp] [datetime] NOT NULL,
CONSTRAINT [PK_Uptime] PRIMARY KEY CLUSTERED 
(
[StateLogID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,                     ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[StateLog]  WITH CHECK ADD  CONSTRAINT [FK_Uptime_Products] FOREIGN    KEY([ProductID])
REFERENCES [dbo].[Product] ([ProductID])
GO

ALTER TABLE [dbo].[StateLog] CHECK CONSTRAINT [FK_Uptime_Products]
GO

I have this and it's not enough:

select top 5 [ProductName], [TimeStamp]
from [Product]
inner join StateLog on [Product].ProductID = [StateLog].ProductID
where [Status] = 0 order by TimeStamp desc;

(My query givess the 5 lastest TimeStamp's where Status is 0(false).)

But I need a thing more: Where there is a set of lastest TimeStamps for a product where Status is 0, i only want the earlist of them (not the lastet).

Example: Let's say for Product X i have:

TimeStamp1(status = 0) TimeStamp2(status = 1) TimeStamp3(status = 0) TimeStamp4(status = 0) TimeStamp5(status = 1) TimeStamp6(status = 0) TimeStamp7(status = 0) TimeStamp8(status = 0)

Correct answer would then be:: TimeStamp6, because it's the first of the lastest timestamps.

© Stack Overflow or respective owner

Related posts about sql