473,796 Members | 2,867 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

query help: need to return 2nd from top record

i need to retrieve the most recent timestamped records with unique
names (see working query below)

what i'm having trouble with is returning the next-most-recent records
(records w/ id 1 and 3 in this example)

i also need to return the 3rd most recent, 4th, 5th and 6th most recent
- i figure if i can get the 2nd working, 3rd, 4th, etc will be cake

thanks,
brett

-- create and populate table
drop table atest
create table atest(id int not null, name char(10), value char(10),
timestamp datetime)

insert into atest values (1,'a','2','1/1/2003')
insert into atest values (2,'a','1','1/1/2004')
insert into atest values (3,'b','2','1/1/2003')
insert into atest values (4,'b','3','1/1/2002')
insert into atest values (5,'b','1','1/1/2004')

-- select most recent records with distinct "name"s
select a.* from atest as a
where a.id = (select top 1 b.id from atest as b
where b.name = a.name
order by timestamp desc )

/*
query results for above query (works like a charm)
2 a 1 2004-01-01 00:00:00.000
5 b 1 2004-01-01 00:00:00.000
*/

Jul 20 '05 #1
6 4354
On 23 Nov 2004 11:36:10 -0800, Toucan wrote:
i need to retrieve the most recent timestamped records with unique
names (see working query below)

what i'm having trouble with is returning the next-most-recent records
(records w/ id 1 and 3 in this example)

i also need to return the 3rd most recent, 4th, 5th and 6th most recent
- i figure if i can get the 2nd working, 3rd, 4th, etc will be cake


Hi Brett,

Here's a solution that works for 1st, 2nd, etc and also avoids the
proprietary T-SQL TOP keyword:

DECLARE @Rank int
SET @Rank = 2
SELECT a.*
FROM atest AS a
WHERE (SELECT COUNT(*)
FROM atest AS b
WHERE b.name = a.name
AND b.timestamp >= a.timestamp) = @Rank

By the way - try to avoid using reserved words as columns names!

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #2
thanks!
that works almost perfectly
there's one case where it fails

insert into atest values (6,'b','xxx','1/1/2004')

set rank to 1

run query and no rows are returned for the "b" rows

any other ideas?
brett

ps. i'll do better naming my columns next time :^)

Jul 20 '05 #3
On 23 Nov 2004 14:29:43 -0800, Toucan wrote:
thanks!
that works almost perfectly
there's one case where it fails

insert into atest values (6,'b','xxx','1/1/2004')

set rank to 1

run query and no rows are returned for the "b" rows


Hi Brett,

And I guess that 2 rows will be returned when yoou set rank to 2. This is
because there is a tie: the rows with id 5 and 6 tie for most-recent
timestamp. You didn't include this possibility in your original post. Now
that you did, you still didn't specify what results you want. So before I
can tweak the query, I need some answers:

* With this data, would you want to see the row with id 5, with id 6 or
both if you use @rank = 1
* Which row(s) would you want if you set @rank to 2, 3, ... with this
data?

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #4
Hey Hugo,

sorry for not being clear - it didn't occur to me until i saw the ">="
in the query

you're correct, 2 rows are returned when rank = 2

what i'd like to see:

rank 1: either 5 or 6 (tie broken arbitrarily)
rank 2: whichever row lost the tie-break
rank 3: row 3

thanks again for all your help,
brett

Jul 20 '05 #5
On 23 Nov 2004 15:47:32 -0800, Toucan wrote:
what i'd like to see:

rank 1: either 5 or 6 (tie broken arbitrarily)
rank 2: whichever row lost the tie-break
rank 3: row 3

thanks again for all your help,


Hi Brett,

Well, there is no such thing as an "arbitraril y" choice in SQL Server,
you'll have to tell SQL Server how to decide (or else it will return
either all rows or none, as you see). Of course, YOU can make an arbitrary
choice, but there has to be SOME choice, it has to be based on data in the
table and it has to be such that there will never be cases where there
still remains a tie.

As an example: if you decide to use "lowest ID value" as tiebreaker (you
didn't include PRIMARY KEY or UNIQUE in the table, but name and sample
data suggest that this is a key, therefor it would satisfy the condition
that no two rows will ever tie with this extra condition):

DECLARE @Rank int
SET @Rank = 1
SELECT a.*
FROM atest AS a
WHERE (SELECT COUNT(*)
FROM atest AS b
WHERE b.name = a.name
AND ( b.timestamp > a.timestamp
OR (b.timestamp = a.timestamp and b.id < a.id))) = @Rank - 1
Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 20 '05 #6
hugo,

perfect!

thank you so much
if you're ever in austin, tx, i'll buy you a beer!

brett

Jul 20 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2528
by: Ralph Freshour | last post by:
I'm not sure the follow multiple table query is the right way to do what I need to do although it seems to be working: $php_SQL = "SELECT * ". "FROM basics, personal, photos ". "WHERE basics.member_name = personal.member_name ". "AND basics.member_name = photos.member_name ". "AND basics.account_creation_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
5
2081
by: jason | last post by:
I could sure use some conceptualization and query help with a Page Watch System I am building in Access 2000 and Asp. I need to cycle through databae and generate a compiliation query email that notifies a person of yacht(s) that have changed on our website: Key database tables ---------------------------------------------------------------------------- Customer (1) --->> (many) Customer_Boats (many)<<---- Boat (1)
20
10165
by: | last post by:
If I need to check if a certain value does exist in a field, and return either "yes" or "not" which query would be the most effestive?
1
1198
by: steven.fafel | last post by:
I have been working with SQL for a while...but I am stumped. I can not seem to get my arms around this query....can anyone help... Here it is: Table = 12 rows, 4 columns (id, name, amount, date) row1 = 771, "steve", $50.00, "01/01/2005" row2 = 772, "steve", $100.00, "01/11/2005" row3 = 773, "steve", $200.00, "01/11/2005" row4 = 774, "dave", $300.00, "01/01/2005"
8
17224
by: Bill | last post by:
Hello out there; This may be a challenge but I'm certain it's possible but I can't seem to figure out how. I have a table that has several date fields, e.g., Date1, Date2, Date3, Date4 ... etc. I wish to find out either of two things for each row. 1) What is the maximun date in any of the date fields in the row.
2
1614
by: Jamie | last post by:
Hello, Please can you help me. The Booking Detail table shows each leg of a journey. BookingRef 1 is a booking for an adult and a child to fly from London to Paris and return. BookingRef 2 is a booking for an Adult to fly from London to New York via Paris and then return. PassType A is an Adult ticket and PassType C is a Child ticket.
7
1719
by: John | last post by:
hi, i have created a search form, and i want to search for a specific item in a field. e.g. i have a field called colour, which has record1 = 'red, blue, green' and another record2 = 'red' now, when i do the search, and only type in red, to search for red, it only brings back record 2, and not record 1 as well.
8
3482
by: chrisdavis | last post by:
I'm trying to filter by query or put those values in a distinct query in a where clause in some sort of list that it goes through but NOT at the same time. Example: ROW1 ROW2 ROW3 ROW4 , etc. I want to go to the first row, do a WHERE statement, return the
2
2752
by: jennk | last post by:
i am working in Access 97, our database tables are linked from ODBCsqlsvr (not even sure what that means). i have a table where each record has a unique customer and their order information. there are 20 possible items to be ordered. i need a query that will return a unique row for every item ordered. if the same customer (record) orders 3 items, i need the query to return 3 rows. Each row will have the same customer info (name, address,...
0
1195
by: sara | last post by:
Hi - I posted this earlier and didn't get any response. Hopefully someone can help?? I have a table keeping track of employees' jobs in a location. So, Store #1 Manager #353, AsstMgr #556 Store #2 Manager #776, AsstMgr #132 etc.
0
10452
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10003
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6785
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.