I have 3 tables as:
Salesperson
1)ID
2)Name
3)Age
4)Salary
Customer
1)ID
2)Name
3)City
4)IndustryType
Orders
1)Number
2)Order_date
3)cust_id
4)salesperson_id
5)Amount
Here is the problem: find the largest order amount for each salesperson and the associated order number, along with the customer to whom that order belongs.
While implementing this
Select salesperson_id,Numbers As ordernum,Amount
from dbo.Orders As Ord Inner Join
(
Select salesperson_id,Max(Amount) as MaxOrder
from dbo.Orders
group by salesperson_id
) as TopOrder
on TopOrder.salesperson_id = Ord.salesperson_id
where TopOrder.MaxOrder=Ord.Amount
but it shows an error:
Msg 209, Level 16, State 1, Line 1
Ambiguous column name 'salesperson_id'.
You have two salesperson_id in your query, one in the table Orders and one in the subquery TopOrder.
Best practice is always to qualify the field name with the table name or alias.
I don't know if sql server supports the using keyword. The only db I know that does is redbrick. You might have to change
using (saleperson_id)
to
where toporder.salesperson_id = orders.salesperson_id
select sp.Name, od.Numbers, Max(od.Amount)
from SalesPerson as sp left join Orders as od on sp.ID = od.salesperson_id
Group By sp.ID
having od.Amount = Max(od.Amount)
This query will help you list all the sale person name and oder number of order with maximum amount Try this and feedback me whether it helps you or not
Try:
Select Ord.salesperson_id,Numbers As ordernum,Amount
from dbo.Orders As Ord Inner Join
(
Select salesperson_id,Max(Amount) as MaxOrder
from dbo.Orders
group by salesperson_id
) as TopOrder
on TopOrder.salesperson_id = Ord.salesperson_id
where TopOrder.MaxOrder=Ord.Amount
select p_orders.salesperson_id,number as 'OrderNum',amount from p_orders
INNER JOIN
(
select salesperson_id,MAX(amount) as 'MAXORDER' from p_orders group by salesperson_id
) as TopOrderAmountPerPerson
ON TopOrderAmountPerPerson.salesperson_id=p_orders.salesperson_id
and p_orders.amount=TopOrderAmountPerPerson.maxorder
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.