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.
Author |
Topic |
michal_milena
Starting Member
1 Post |
Posted - 2014-05-11 : 11:36:03
|
Hello I'm new here, so I hope that it's good place for ask:)Generally I'm trying to refresh my knowledge of t-sql after 3 year. I'm learning on Microsoft Northwind model base - I cannot resolve one query.I want fix data from 3 tables - Order Details, Orders, and Products. Becouse I want to retrieve - which product is the most expensive in each order. To get the most expensive prices in orders is simply, becouse I can use this query:SELECTOrderID, MAX(UnitPrice)ASMaxFROM[order details]GROUPBYOrderIDBut If I want to add one more column, as name of product, I would able do something like this:SELECTOrderID, MAX(UnitPrice)AS Max, OD.UnitPriceFROM[order details] as OD join Products as P ON OD.ProductID = P.ProductIDGROUPBYOrderID, OD.UnitPriceBut it mess everything - it don't give result:(I don't know how to resolve it? I suppose I need use subquery, but how?I will be appreciated for any help |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2014-05-11 : 20:48:28
|
Here are various method to do that. Subquery is the least prefer method. -- Using derived tableselect *from [order details] d inner join ( SELECT OrderID, MAX(UnitPrice) AS MaxPrice FROM [order details] GROUP BY OrderID ) m on d.OrderID = m.OrderID and d.UnitPrice = MaxPrice-- Using window ranking functionselect *from ( select *, rn = row_number() over (partition by OrderID order by UnitPrice desc) from [order details] ) dwhere d.rn = 1-- using subquerySELECT OrderID, MAX(UnitPrice) AS Max, (select top 1 ProductID from [order details] x where x.OrderID = d.OrderId order by UnitPrice desc) as ProductIDFROM [order details] dGROUP BY OrderID You can also use APPLY operator to achieve this. KH[spoiler]Time is always against us[/spoiler] |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2014-05-12 : 07:11:55
|
Another way using EXISTSSELECT OD.OrderID,ProductName,OD.UnitPriceFROM [order details] as OD join Products as P ON OD.ProductID = P.ProductIDWHERE NOT EXISTS (SELECT 1FROM [order details]WHERE OrderID = OD.OrderIDAND UnitPice > OD.UnitPrice) ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|
|
|