473,405 Members | 2,338 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

selecting top n via a subquery isn't working

The SQL statement I am using is -

Expand|Select|Wrap|Line Numbers
  1. SELECT [2010 chicks rung].bird_id, [2010 chicks rung].nest_rear, [2010 chicks rung].date, [2010 chicks rung].time, [2010 chicks rung].weight_g
  2. FROM [2010 chicks rung]
  3. WHERE [2010 chicks rung].bird_id IN
  4.     (SELECT TOP 4 bird_id
  5.     FROM [2010 chicks rung] AS Dupe
  6.     WHERE Dupe.bird_id = [2010 chicks rung].bird_id
  7.     ORDER BY Dupe.bird_id DESC)
  8. ORDER BY [2010 chicks rung].bird_id,  [2010 chicks rung].nest_rear, [2010 chicks rung].date, [2010 chicks rung].time, [2010 chicks rung].weight_g;
I have tried removing the ORDER BY in the subquery.

Basically it gives me all the results and not the top 4 as I wish. Any ideas as to how to correct this?

Thank you,

Lizy
Feb 18 '11 #1
16 2778
MikeTheBike
639 Expert 512MB
Hi

I think I might try it likr this

Expand|Select|Wrap|Line Numbers
  1. SELECT [2010 chicks rung].bird_id, [2010 chicks rung].nest_rear, [2010 chicks rung].date, [2010 chicks rung].time, [2010 chicks rung].weight_g
  2. FROM [2010 chicks rung] INNER JOIN (SELECT TOP 4 bird_id FROM [2010 chicks rung] ORDER BY bird_id DESC) as Dupe ON Dupe.bird_id = [2010 chicks rung].bird_id
  3. ORDER BY [2010 chicks rung].bird_id, [2010 chicks rung].nest_rear, [2010 chicks rung].date, [2010 chicks rung].time, [2010 chicks rung].weight_g;
??

MTB
Feb 18 '11 #2
Thank you for replying.

The statement you suggested has given a bizarre output! For a single bird_id it has duplicated each record 6 times - there is now only one bird_id.

ie.

bird_id, date

1 01/01/2001
1 01/01/2001
1 01/01/2001
1 01/01/2001
1 01/01/2001
1 01/01/2001
1 01/01/2001
1 02/01/2001
1 02/01/2001
1 02/01/2001
1 02/01/2001
1 02/01/2001
1 02/01/2001
1 02/01/2001

I tried using a GROUP BY function within the subquery to no avail either. I am really stuck on this and will continue to search google.

Lizy
Feb 18 '11 #3
MikeTheBike
639 Expert 512MB
Without any knowledge of you data it is hard to know what you are expecting.

I assume the other three fields are also retuned also!!

MTB
Feb 18 '11 #4
gershwyn
122 100+
I'm not sure the point of the WHERE clause in your subquery. You don't need to compare this to the main table at all, you're just looking for a list of the top 4.

Also, if there are multiple records for the same bird_id (which I suspect there are), your subquery might return the same ID more than once. If you're looking for all the data on the top 4 unique birds, you want to add the DISTINCT keyword as well.

Expand|Select|Wrap|Line Numbers
  1. SELECT [2010 chicks rung].bird_id, [2010 chicks rung].nest_rear, [2010 chicks rung].date, [2010 chicks rung].time, [2010 chicks rung].weight_g
  2. FROM [2010 chicks rung]
  3. WHERE [2010 chicks rung].bird_id IN
  4. (SELECT DISTINCT TOP 4 bird_id
  5. FROM [2010 chicks rung] AS Dupe
  6. ORDER BY Dupe.bird_id DESC)
  7. ORDER BY [2010 chicks rung].bird_id, [2010 chicks rung].nest_rear, [2010 chicks rung].date, [2010 chicks rung].time, [2010 chicks rung].weight_g;
This should return all the data for the records with a bird_id among the 4 highest in the table. If that's not what you need, please respond to clarify (and sample data always helps.)
Feb 18 '11 #5
Thank you for the responses, what I am after is:

-the fourth chronological date (and the rest of data in this record) for each bird_id.

In some instances there are 4 dates for each bird_id, in some there are 5 or 6. For this reason I decided it would be best to collect the top four dates associated with each bird_id and then perform a MOD 4 function on this (possibly using an autonumber key).

I originally obtained my query (and subquery) from many different websites that say this query will get the top n records per group, in my case the bird_id is the group. I don't know why it isn't working or how to fix it despite much searching and fiddling around with the SQL...

I hope this makes a bit more sense? I need to end up with a date for every bird_id, not filter the bird_id's themselves.
Feb 18 '11 #6
Rabbit
12,516 Expert Mod 8TB
You say that you're trying to get the 4th date but your query makes no reference to the date field. You are in fact filtering on bird ID which isn't actually doing any filtering at all since your bird ID is not unique and you are joining on bird ID.

Your subquery needs to take into account the date and your where clause needs to filter by date and not bird id.
Feb 18 '11 #7
Thank you, you make a very obvious valid point!

My date field is not unique either, it is the combination of the bird_id and date within this that is unique...I'm now not sure how to proceed.
Feb 18 '11 #8
ADezii
8,834 Expert 8TB
@Elizabeth - I'm sure that I can create a relatively simple Code based solution to the problem, but SQL would definitely be the way to go. Should all else fail, doubt it with MikeTheBike, gershwyn, and Rabbit on the case, I'm sure that I can come up with something for you.
Feb 18 '11 #9
Rabbit
12,516 Expert Mod 8TB
I would do something along the lines of
Expand|Select|Wrap|Line Numbers
  1. SELECT UniqueID, DateField
  2. FROM Table1 AS x
  3. WHERE DateField IN
  4.   (SELECT TOP 4 DateField
  5.    FROM Table1
  6.    WHERE Table1.UniqueID = x.UniqueID
  7.    ORDER BY DateField DESC)
However, as the code states, it's selecting the top 4. But your words seem to say that you don't actually want top 4. You say you want just the fourth date even though for some reason you're using top 4. In such a case, you would need to use a subquery ranking.
Feb 18 '11 #10
ADezii
8,834 Expert 8TB
@Rabbit - The way I read it is:
For each ID, return the 4th Record with all Fields, chronologically by Date. The combination of [ID] and [Date], as stated by the Op are Unique, so ties would not be a consideration. the Result Set would be 1 Record for each [ID] (the 4th chronologically per [ID]). Do you see it this way?
Feb 18 '11 #11
Rabbit
12,516 Expert Mod 8TB
That's how I think the OP wants it. But her use of TOP 4 contradicts that assumption. I don't know if the miscommunication is with her choice of tactic or her choice of wording.
Feb 18 '11 #12
ADezii
8,834 Expert 8TB
@Elizabeth - before we go any further, I really think that we need to know exactly what the expected Results are. Given the Sample Data and the Results posted below, is this correct?
Expand|Select|Wrap|Line Numbers
  1. Primary_Key    Bird_ID    Date       Field3 Field4  Field5
  2. 1                1       1/15/2010    N/A    N/A    N/A
  3. 2                1       1/31/2010    N/A    N/A    N/A
  4. 3                1       3/23/2010    N/A    N/A    N/A
  5. 4                1       4/15/2010    N/A    N/A    N/A
  6. 5                1       6/19/2010    N/A    N/A    N/A
  7. 6                1       7/1 /2010    N/A    N/A    N/A
  8. 7                1      10/29/2010    N/A    N/A    N/A
  9. 8                1      11/23/2010    N/A    N/A    N/A
  10. 9                4       2/24/2010    N/A    N/A    N/A
  11. 10               4       5/29/2010    N/A    N/A    N/A
  12. 11               4       8/30/2010    N/A    N/A    N/A
  13. 12               4       9/2 /2010    N/A    N/A    N/A
  14. 13               4      12/21/2010    N/A    N/A    N/A
  15. 14               4      12/31/2010    N/A    N/A    N/A
Results (my interpretation):
Expand|Select|Wrap|Line Numbers
  1. Primary_Key    Bird_ID    Date       Field3 Field4  Field5
  2. 4                1       4/15/2010    N/A    N/A    N/A
  3. 12               4       9/2 /2010    N/A    N/A    N/A
Feb 18 '11 #13
ADezii that is exactly what I am after! I have only been trying to get the top 4 as I couldn't think of another way of then selecting the 4th record for each...

I am still failing to get even the TOP 4

Thank you so much for all the replies
Feb 21 '11 #14
ADezii
8,834 Expert 8TB
@Elizabeth - now that we have a crystal clear understanding of exactly what the results should be, I'm sure that a solution will be forthcoming. SQL is definitely not my area of expertise, but I can always arrive at a Code-based solution as a worse care scenario, which I don't think will become necessary. Stay tuned to this channel! (LOL).

P.S. - Sounds like this should be a piece of cake for Rabbit, MikeTheBike, or gershwyn.
Feb 21 '11 #15
Rabbit
12,516 Expert Mod 8TB
To get the N-th record of a set of records, I would use a ranking subquery. Kind of like this:
Expand|Select|Wrap|Line Numbers
  1. SELECT ID, DateField
  2. FROM Table1 AS x
  3. WHERE (
  4.    SELECT Count(*)
  5.    FROM Table1
  6.    WHERE DateField <= x.DateField
  7.       AND ID = x.ID
  8.    ) = 4
Feb 21 '11 #16
ADezii
8,834 Expert 8TB
@Elizabeth - As expected, Rabbit nailed it. Substituting Field and Table Names based on the Sample Data in Post #13, and adding an ORDER BY Clause, the final SQL Statement would be:
Expand|Select|Wrap|Line Numbers
  1. SELECT [Primary_Key], [Bird_ID], [Date], [Field3], [Field4], [Field5]
  2. FROM tblData AS x
  3. WHERE ( 
  4.    SELECT Count(*) 
  5.    FROM tblData 
  6.    WHERE [Date] <= x.[Date] 
  7.       AND [Bird_ID] = x.[Bird_ID] 
  8.    ) = 4
  9. ORDER BY [Bird_ID];
Feb 21 '11 #17

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Michael Flanagan | last post by:
Of course "echo" is working, but I've got a case where php doesn't seem to be sending out the result of an "echo." I'm probably doing something wrong, but I can't see it. I've got the following...
1
by: Sebastian Aguilera | last post by:
Hi everyone. I have some troubles using the unserialize() function. I have serialized an array and that works perfect: echo '<input type="hidden" name="vardekedja" value="'.serialize($_POST...
6
by: Stijn Goris | last post by:
HI all, I have created a script that allows a user to upload a picture. I have an IIS server runing on my own pc but the actual site runs an Apache server. The upload script worked perfectly on...
6
by: SB | last post by:
This while loop keeps repeating even when a correct character is entered.... cout<<endl<<"What day would you like to schedule the appointment?"<<endl; cout<<endl<<"Enter 'M' for Monday, 'T' for...
9
by: Simon | last post by:
I've got a simple and repetitive bit of code for a function in a C implementation of the card game 31s I'm working on. BTW, I am a bit of a novice at C; for the past couple of years I was using...
10
by: sp | last post by:
The application is written in Visual Basic / .NET and working without problems under Windows XP, Windows 2000, Windows 2003 but it isn't working under Windows ME and Windows 98 - the computer...
2
by: PrinceMhul | last post by:
var objListBox = document.getElementById('catalist'); var val = objListBox.value; var txt = dyevalue00.value; document.getElementById(val).value = txt; To explain real quick, this is for a...
0
by: DougRenwick | last post by:
I'm an trying to prevent my application from stealing the focus from the application that launched it. Overriding the ShowWithoutActivation property returns a value of true but does not prevent the...
7
by: nassausky | last post by:
I acquired a very basic redirect script from: http://www.minisitegallery.com/blog/php-javascript-countdown-script-with-timezone-setting.html which is supposed to count down to a specified date and...
12
by: Hendor | last post by:
Hi all. I've recently set up Apache 2.2 with PHP 5.2 and MySQL 5.1. I played around with SQL a bit, and now I'm trying to access it with PHP. I currently have the code: <?php #...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.