473,394 Members | 2,020 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,394 software developers and data experts.

Select lowest two prices from item list grouped by item id

11
Hi. New to sql

I have an items table and I want to select the lowest two priced rows per item id.

i.e.

Expand|Select|Wrap|Line Numbers
  1. item        vendor        price
  2. 12            xyz         1
  3. 12            aaa         2
  4. 12            zzz         1.5
  5.  
  6. 13            xyz         3
  7. 13            aaa         1.5
  8. 13            zzz         1
  9.  
  10. Would return: 
  11.  
  12. item        vendor        price
  13. 12            xyz         1
  14. 12            zzz         1.5
  15.  
  16. 13            aaa         1.5
  17. 13            zzz         1
Also, how do I get the spaces between the items to show up as I type them? The table I type is easy to read, the one shown doesn't have the same spacing between fields.

Thanks in advance!
Mar 27 '16 #1

✓ answered by mbizup

What you're describing (lowest two PER ID) is a Top N Per Group query. Subqueries are one way to accomplish this. Take a look at Allen Browne's post here, under the heading "Top N Records Per Group":
Subquery Basics

You'll need the DESC Keyword to get the lowest.

{Edit}Relevant excerpt from Allen's article.
TOP n records per group

You want the three most recent orders for each client. Use a subquery to select the 3 top orders per client, and use it to limit which orders are selected in the main query:
Expand|Select|Wrap|Line Numbers
  1. SELECT   Orders.CustomerID, Orders.OrderDate, Orders.OrderID
  2. FROM     Orders
  3. WHERE    Orders.OrderID IN
  4.    (SELECT TOP 3 OrderID                            
  5.     FROM     Orders AS Dupe                              
  6.     WHERE    Dupe.CustomerID = Orders.CustomerID        
  7.     ORDER BY Dupe.OrderDate DESC
  8.            , Dupe.OrderID DESC) 
  9. ORDER BY Orders.CustomerID
  10.        , Orders.OrderDate
  11.        , Orders.OrderID;
Points to note:
  • Since we have two copies of the same table, we need the alias.
  • Like EXISTS in the first example above, there is no problem with the subquery returning multiple records. The main query does not have to show any value from the subquery.
  • Adding the primary key field to the ORDER BY clause differentiates between tied values.
{/Edit}

5 2999
jforbes
1,107 Expert 1GB
The TOP Keyword can limit the results to two.
ORDER BY will sort the list before TOP is applied.
Expand|Select|Wrap|Line Numbers
  1. SELECT TOP 2 item, vendor, price
  2. FROM tblPrice
  3. ORDER BY price DESC

You can use the [CODE/] Button to Format Text on the page.
Mar 28 '16 #2
mbizup
80 64KB
What you're describing (lowest two PER ID) is a Top N Per Group query. Subqueries are one way to accomplish this. Take a look at Allen Browne's post here, under the heading "Top N Records Per Group":
Subquery Basics

You'll need the DESC Keyword to get the lowest.

{Edit}Relevant excerpt from Allen's article.
TOP n records per group

You want the three most recent orders for each client. Use a subquery to select the 3 top orders per client, and use it to limit which orders are selected in the main query:
Expand|Select|Wrap|Line Numbers
  1. SELECT   Orders.CustomerID, Orders.OrderDate, Orders.OrderID
  2. FROM     Orders
  3. WHERE    Orders.OrderID IN
  4.    (SELECT TOP 3 OrderID                            
  5.     FROM     Orders AS Dupe                              
  6.     WHERE    Dupe.CustomerID = Orders.CustomerID        
  7.     ORDER BY Dupe.OrderDate DESC
  8.            , Dupe.OrderID DESC) 
  9. ORDER BY Orders.CustomerID
  10.        , Orders.OrderDate
  11.        , Orders.OrderID;
Points to note:
  • Since we have two copies of the same table, we need the alias.
  • Like EXISTS in the first example above, there is no problem with the subquery returning multiple records. The main query does not have to show any value from the subquery.
  • Adding the primary key field to the ORDER BY clause differentiates between tied values.
{/Edit}
Mar 28 '16 #3
kdmrr
11
Thanks, I'll try this tonight.
Mar 28 '16 #4
kdmrr
11
Thanks!! It worked perfectly
Apr 2 '16 #5
NeoPa
32,556 Expert Mod 16PB
I just added the relevant part of that article to Miriam's post as it's been selected as Best Answer. Where possible, they should have the answer plainly visible so searchers can get a very quick hit when they land on a Bytes.com page.
Apr 3 '16 #6

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

Similar topics

1
by: fotis | last post by:
hi there can anybody tell me if it's possible and how can i change the name of a CheckedListBox item.I have used the Add method to insert the item. thank you
2
by: touf | last post by:
Hi how can we select an item in a listview by code?
1
by: BillyB | last post by:
I have a context menu tied to a list box. When I right-click on an item, I'd like that item to be selected before the context menu invokes, similar to how Outlook Express works when right-clicking...
6
by: nasirmajor | last post by:
Dear all, a simple quetion as usual I have a html select list. e.g <select class="text" name="bmonth" runat="server" id="bmonth"> <option selected="selected" value="0"></option> <option...
3
by: warthogweb | last post by:
I have a contact list with 'name', 'www' and 'email'. Some entries do not have 'www' or 'email' or both. I want to save space and make the 'name' a link to the web address only where a web address...
13
by: Mel | last post by:
i would like set my <Selectoptions from a list AFTER the form is created and a list of urls for those selections from javascript. How can i do this My select may have a list like: "Go to One",...
2
by: kranthi4uonly | last post by:
how to select all items in list box by butoon click in c# can any one give the smaple code for this
3
by: MikeB | last post by:
I'm trying to do something and I'm sure there is a good technique for it, but I just can't figure it out. I have some member records in a database. I want to display a list of them, and have a...
0
by: xiaobb16 | last post by:
golden suppliers,lowest prices .cover all brand products accept PAYPAL . Prices are at the lowest notch.air jordan air max R3 R4 NZ TN shoes www.cheapnetstore.cn
1
by: MasterStarr | last post by:
I Have A Music Player I Made Using A Tutorial In Visual basic 2008 And The Play Button For This Player Plays The Songs Fine, But The Problem Is The Code: AxWindowsMediaPlayer1.Ctlcontrols.next() ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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...

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.