0
我們可以解決以下情況下與加入,我已經和窗口功能解決Sql join解決方案是否適用於以下情況?
關係:在下面的表中,Orders表中的每一個訂單,與給定的客戶通過引用ID中的cust_id外鍵列相關客戶表中的列。
問題:查找每個銷售員和相關訂單號以及該訂單所屬的客戶和銷售人員姓名的最大訂單金額。
Create Table Salesperson
(
ID int,
name varchar(100),
age float,
salary money
);
Create Table Orders
(
Number int,
order_date datetime,
cust_id int,
salesperson_id int,
Amount money
);
Create Table Customer
(
ID int,
name varchar(100),
city varchar(100),
IndustryType varchar(100)
);
insert into Salesperson values
(1,'Rohit',25,50000),
(2,'Pramod',25,50000),
(3,'Atul',25,50000);
insert into Orders values
(1,getdate(),101,1,50000),
(2,getdate(),101,1,500000),
(3,getdate(),102,1,10000),
(4,getdate(),101,2,5000),
(5,getdate(),102,2,700000),
(6,getdate(),102,2,10000);
insert into Customer values
(101,'Altu','bhopal','IT'),
(102,'bltu','bhopal','ITES'),
(103,'cltu','bhopal','NW');
解決方案與窗函數:
with CTE_MaxAmount
as
(
select max(amount) over (partition by salesperson_id) as amount,
dense_rank() over (partition by salesperson_id order by amount) as rowid,
cust_id,
salesperson_id,number
from Orders with(nolock)
)
select ct.amount,
ct.cust_id,
c.name as customername,
s.name as salesman,
ct.salesperson_id,
number as OrderNumbner
from Customer c
join CTE_MaxAmount ct
on (c.id = ct.cust_id)
join Salesperson s
on (s.id = ct.salesperson_id)
where rowid = 1;
感謝您的幫助.. !!!! – Rohit