So I have Two tables
One is "Orders" containing following columns
- OrderID (int)(primary key)
- CustomerID (nchar(5))
- OrderDate (Datetime)
Second is "Order Details" containing following columns
- OrderID (int)
- ProductID (int) 1 and 2 combined is the primary key for this table.
- UnitPrice (money)
- Quantity (smallint)
- Discount (real)
Now write a query to find out the OrderId, ProductId, OrderDate and UnitPrice of the products having highest price in an order.
The price of product is calculated as (UnitPriceQuantity - DiscountUnitPrice*Quantity). The operation has to be performed for each OrderID in "Orders".
I am putting up Sample Data.Here is Input table "Orders"-
OrderID CustomerID OrderDate
1000 1 11-09-2016
1001 1 12-10-2016
Here is Another Input table "Order Details"-
OrderID ProductID UnitPrice Quantity Discount
1000 11 5 15 0.0
1000 13 25 2 0.0
1000 14 7 11 0.0
1001 5 30 3 0.0
1001 6 50 2 0.12
Here is the expected Output
OrderID ProductID OrderDate UnitPrice
1000 14 11-09-2016 7
1001 5 12-10-2016 30
I have already tried it using Joins. Here is the query I have tried
DECLARE @OID INT=10248;
SELECT d.OrderID,d.ProductID,d.UnitPrice
INTO #Temp3
from [Order Details] d
INNER JOIN
(Select TOP 1 OrderID,ProductID,MAX(UnitPrice*Quantity-UnitPrice*Discount*Quantity)as Maxi from [Order Details]
where OrderID=@OID
GROUP BY OrderID,ProductID
ORDER BY Maxi DESC) e ON e.OrderID=d.OrderID and e.ProductID=d.ProductID;
select T.OrderID,T.ProductID,o.OrderDate,T.UnitPrice
from Orders o
INNER JOIN #Temp3 T
ON o.OrderID=T.OrderID;
The only problem with this query is that I have to provide the OrderID. I want it to be executed for every OrderID in "Orders"
join
s and try it first and post a question if you get stuck.sql-server
andtsql
tags based on the syntax in the question