473,770 Members | 5,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Select first n rows of table

Let us say that I have a table with two sets of values as such:

Item Extension
--- ----
100023 1
100025 1
100025 2
100028 1
100029 1
100029 2
100029 3
[...]

Note that a given item number can appear multiple times if it has more
than one extension number.

I want to be able to select the first N entries as grouped by item
number. So if N = 3, that would return 100023, 100025 and 10028 with
their associated extentions. I would also like to be able to select
say, the 2nd through 9th entries grouped by item number.

I've tried something like this to give me row counts:

select rank = count(1), t1.item, t1.extension
from ItemTable t1 inner join itemTable t2
on t1.item >= t2.item
group by t1.item, t1.extension
order by rank

But that gives me this sort of result:

Rank Item Extension
---- --- ----
1 100023 1
3 100025 1
3 100025 2
4 100028 1
7 100029 1
7 100029 2
7 100029 3
[...]
Any suggestions would be welcome.

Mar 28 '06 #1
2 7497
SQL
Here are 2 ways distinct and using group by
It's using a temp table with the identity function
The problem that you have is that you implemented a DENSE_RANK instead
of RANK
In SQL Server 2005 this is much easier of course

CREATE TABLE Rankings (Item int , Extension int)
INSERT INTO Rankings
SELECT 100023,1 UNION ALL
SELECT 100025,1 UNION ALL
SELECT 100025,2 UNION ALL
SELECT 100028,1 UNION ALL
SELECT 100029,1 UNION ALL
SELECT 100029,2 UNION ALL
SELECT 100029,3

SELECT IDENTITY(INT, 1,1) AS Rank ,Item,Extension
INTO #Ranks FROM Rankings WHERE 1=0

INSERT INTO #Ranks
SELECT Item,Extension FROM Rankings
ORDER BY Item,Extension

declare @top int
select @top=3 -- this would be you top n...
SELECT distinct z.Ranking ,t2.Item,r.Exte nsion
FROM (SELECT (SELECT COUNT( DISTINCT t1.Item) FROM Rankings t1 WHERE
z.Item>= t1.Item)AS Ranking, z.Item
FROM #Ranks z ) z
JOIN #Ranks t2 ON z.Item = t2.Item
join Rankings r on r.Item = z.item
and r.Item = t2.Item
and ranking <=@top
ORDER BY z.Ranking
also a temp table with identity is much faster than a running count
Let me know if it works for you

Denis the SQL Menace
http://sqlservercode.blogspot.com/

Mar 28 '06 #2
also a temp table with identity is much faster than a running count
Let me know if it works for you


Thanks. I was trying to avoid using a temp table, but this is a good
solution.

Mar 30 '06 #3

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

Similar topics

9
10773
by: Rowland Hills | last post by:
I have a table which is returning inconsistent results when I query it! In query analyzer: If I do "SELECT * FROM TABLE_NAME" I get no rows returned. If I do "SELECT COL1, COL2 FROM TABLE_NAME" I get 4 rows returned. In Enterprise manager:
10
3983
by: AC Slater | last post by:
I have 1 table (out of many) that has very poor performance when performing a select into on. The select statement is called multiple times. We've found each call to take almost 1 second... we were expecting less than .1 seconds. The select stmt looks like: select key,data into key_buff, data_buff from tablename where key > curr_key AND key < max_key ORDER by key FETCH FIRST 1 ROW ONLY;
12
7698
by: TP | last post by:
Here is my problem. I need to display a table about which I have no information except the table name. Using metadata I can somehow show the column names and record values. But my table has 1 million rows and if I do a select * then I do get 1 million rows. I want to be able to provide page navigation as google does, page
13
6816
by: RR | last post by:
Hi, It appears that DB2 has an arbitrary restriction on the use of "fetch first N rows". I want to insert into a table from a large table query, but only insert the first N rows: insert into target (select colA,colB from source where conditions fetch first 1000 rows only);
1
4040
by: Diffident | last post by:
Hello All, I am trying to filter rows in a datatable based on filtercriteria and sortcriteria using the datatable.select() method. I am encountering a strange behavior in this process. Here is what I am trying to do... ---------
4
4088
by: Ed L. | last post by:
I think I'm seeing table-level lock contention in the following function when I have many different concurrent callers, each with mutually distinct values for $1. Is there a way to reimplement this function using select-for-update (or equivalent) in order to get a row-level lock (and thus less contention) while maintaining the function interface? The docs seem to suggest so, but it's not clear how to return the SETOF queued_item and also...
6
4849
by: jjturon | last post by:
Can anyone help me?? I am trying to pass a Select Query variable to a table using Dlookup and return the value to same select query but to another field. Ex. SalesManID SalesManName AT Alan Time
2
7722
by: mokazawa1 | last post by:
Hi, I'm using stored procedures in DB2 UDB 8.1.2. In this stored, I execute a select for update command, opening a cursor. Then I update the rows using fetch and current of. The problem is that I want to return the rows for my Java application. But if I set the cursor of the select for WITH RETURN, I get the values, but I cant execute the update. If I dont use WITH return, I execute the update, but I cant get the result set. Any ideas.
5
22773
by: Mahesh S | last post by:
Hi I would like to write a SQL select statement that would fetch rows numbered 50 to 100. Let me clarify, if i say "fetch first 10 rows only", it returns the first 10 rows from the resultset. how do I get a specific subset of rows from the result set if I give a start and end value. For example, retreiving rows 50 to 100 from the resultset.
16
2748
by: Richard Maher | last post by:
Hi, I have this Applet-hosted Socket connection to my server and in an ONevent/function I am retrieving all these lovely rows from the server and inserting them into the Select-List. (The on screen appearance of the Select List grows for the first 5 rows then the scroll bar appears if there's more). So far so good. . . The problem is that none of the rows I'm inserting appear on the screen until I have RETURNed from my function; so If...
0
9595
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9432
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10008
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9873
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...
0
6682
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
5454
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3974
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
3578
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2822
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.