I’m working with a Sybase 12.5 server and I have a table defined as such:
CREATE TABLE SomeTable(
[GroupID] [int] NOT NULL,
[DateStamp] [datetime] NOT NULL,
[SomeName] varchar(100),
PRIMARY KEY CLUSTERED (GroupID,DateStamp)
)
I want to be able to list, per [GroupID], only the latest X records by [DateStamp]. The kicker is X > 1, so plain old MAX() won’t cut it. I’m assuming there’s a wonderfully nasty way to do this with cursors and what-not, but I’m wondering if there is a simpler way without that stuff.
I know I’m missing something blatantly obvious and I’m gonna kick myself for not getting it, but …. I’m not getting it. Please help.
Is there a way to find TOP X records, but with grouped data?
According to the online manual, Sybase 12.5 supports
WINDOWfunctions andROW_NUMBER(), though their syntax differs from standard SQL slightly.Try something like this:
I don’t have an instance of Sybase, so I haven’t tested this. I’m just synthesizing this example from the doc.
I made a mistake. The doc I was looking at was Sybase SQL Anywhere 11. It seems that Sybase ASA does not support the
WINDOWclause at all, even in the most recent version.Here’s another query that could accomplish the same thing. You can use a self-join to match each row of SomeTable to all rows with the same GroupID and a later DateStamp. If there are three or fewer later rows, then we’ve got one of the top three.
Note that you must list the same columns in the
SELECTlist as you list in theGROUP BYclause. Basically, all columns froms1that you want this query to return.