SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Finding the Lowest Cost Supplier
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

DoktorD1313
Starting Member

1 Posts

Posted - 08/21/2013 :  16:12:49  Show Profile  Reply with Quote


Ok, here's what I'm trying to do.

I have a table with four important columns (only four important to this problem, anyway).

One column is ID (the primary key), second is ItemID, third is SupplierID, and the last is Cost.


This table contains one row for every item/supplier pair that exists in the store.

In other words, if a particular caulking is ItemID '871111' and had two suppliers '197' and '62', the table would look like



ID | ItemID | SupplierID | Cost |
| | | |
81 |871111 |197 |1.27 |
82 |871111 |62 |1.17 |
83 |253165 |197 |.95 |
84 |253165 |62 |1.05 |


I'm looking for a query that would return the lowest cost for each unique ItemID in the table to show the lowest cost vendor.


What I'm looking for it to return would be:

ID | ItemID | SupplierID | Cost |
| | | |
82 |871111 |62 |1.17 |
83 |253165 |197 |.95 |


From there I'd be able to update my item file with the primary vendor being the cheapest.

I'm starting to tear my hair out trying to think of how to do this. I have a feeling the answer is staring me in the face. I just can't see it with my tunnel vision.

James K
Flowing Fount of Yak Knowledge

3323 Posts

Posted - 08/21/2013 :  16:22:40  Show Profile  Reply with Quote
SELECT ID, ItemID, SupplierID, Cost
FROM
(
	SELECT *, ROW_NUMBER() OVER (PARTITION BY ItemID ORDER BY Cost ASC) AS RN
	FROM YourTable
)s WHERE RN = 1
Go to Top of Page

sivadss2007
Starting Member

India
18 Posts

Posted - 08/28/2013 :  06:52:44  Show Profile  Reply with Quote


SELECT ID,ItemId,SupplierId,cost,row_number() over (partition by itemid order by cost ) as rowid
into #temp
from table_name

select * from #temp where rowid = 1


P.Siva

Edited by - sivadss2007 on 08/28/2013 06:56:32
Go to Top of Page

sivadss2007
Starting Member

India
18 Posts

Posted - 08/28/2013 :  06:52:45  Show Profile  Reply with Quote


SELECT ID,ItemId,SupplierId,cost,row_number() over (partition by itemid order by cost ) as rowid
into #temp
from table_name

select * from #temp where rowid = 1


P.Siva

Edited by - sivadss2007 on 08/28/2013 06:57:00
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000