2017-03-08 8 views
0

私は窓関数で解決しました以下のケースでは、Sql結合ソリューションが有効でしょうか?

関係:下の表では、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; 

答えて

2

私は質問が英語をSQLに変換する方法を簡単に示す機会ですので、宿題の質問に答えることなく、私の個人的な方針に破壊しています。クエスチョンが構築できるように、質問は正確に表現されます。

各営業担当者の顧客

と共に

select max(Amount) as Amount, salesperson_id from Orders group by salesperson_id 

と関連する注文番号

select o.Number, M.salesperson_id, M.Amount 
from Orders as o join (
    select max(Amount) as amount, salesperson_id 
    from Orders group by salesperson_id 
) as M 
on o.salesperson_id = M.salesperson_id 
and o.Amount = M.Amount 

の最大注文量を見つけます。

select c.name, o.Number, M.salesperson_id, M.Amount 
from Orders as o join (
    select max(Amount) as amount, salesperson_id 
    from Orders group by salesperson_id 
) as M 
on o.salesperson_id = M.salesperson_id 
and o.Amount = M.Amount 
join Customer as c 
on o.cust_id = c.ID 

と販売者名

select s.name as 'salesperson', 
c.name as 'customer', 
o.Number, M.salesperson_id, M.Amount 
from Orders as o join (
    select max(Amount) as amount, salesperson_id 
    from Orders group by salesperson_id 
) as M 
on o.salesperson_id = M.salesperson_id 
and o.Amount = M.Amount 
join Customer as c 
on o.cust_id = c.ID 
join Salesperson as s 
on o.salesperson_id = s.ID 
+0

協力いただきありがとうございます。.. !!!! – Rohit

関連する問題