Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I have the following 3 tables.Im trying to write the following SP:For each sale from the SALES table im trying to find the highestprice from the PRICES table and get addtional details about the user (of that price) from the Users table + Title of the sale from the SALES table.
i wrote the following query, and i managed to get the highest price for each sale with the sale title but i dont know how to get the user details.select s.SaleID , s.Title , p.highfrom Sales sinner join (SELECT SaleID , MAX(Price) as highFROM Prices AS pgroup by SaleID) pon s.SaleID = p.SaleIDThank you for your help!
SwePeso
Patron Saint of Lost Yaks
30421 Posts
Posted - 2009-01-21 : 16:33:23
We have showed you how to use ROW_NUMBER() function before.
SELECT s.SaleID, s.Title, p.Price, u.UserName, u.NameFROM Sales AS SINNER JOIN ( SELECT SaleID, Price, UserName, ROW_NUMBER() OVER (PARTITION BY SaleID ORDER BY Price DESC) AS recID FROM Prices ) AS p ON p.SaleID = s.SaleID AND p.recID = 1INNER JOIN Users AS u ON u.UserName = p.UserName
E 12°55'05.63"N 56°04'39.26"
shaharru
Yak Posting Veteran
72 Posts
Posted - 2009-01-22 : 09:53:00
Yes i know you showed me how to use ROW_NUMBER() , i guess i was fixed on using GROUP BY in this case.Anyway ,Thank you!!
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2009-01-22 : 10:52:58
Also
SELECT s.SaleID, s.Title,t.Price,t.Username,t.NameFROM Sales sCROSS APPLY (SELECT TOP 1 p.Price, p.Username, u.Name FROM Prices p INNER JOIN Users u ON u.Username=p.Username WHERE p.SaleID=s.SaleID ORDER BY p.Price DESC)t