2016-10-19 53 views
0

如果我有一對夫婦的表像下限制註冊數量

Table1 
----------------------------- 
Name      Qty 
----------------------------- 
John      1 
Paul      2 
       ... 
Ringo      1 

Table2 
----------------------------- 
Forename Surname  Cost 
----------------------------- 
John  Smith  123 
John  Jones  815  
Paul  Smith  273 
Paul  Jones  297 
      ... 
Ringo  Smith  755 
Ringo  Jones  334 

,我想建立一個查詢,以便數量從表2返回各子集由有序Table2.Cost並受限於Table1.Qty,返回類似於:

Results 
----------------------------- 
Forename Surname  Cost 
----------------------------- 
John  Jones  815 
Paul  Jones  297 
Paul  Smith  273 
Ringo  Smith  755 

有沒有辦法做到這一點?

+1

你的結果是什麼邏輯?你可以寫你的查詢,並讓我們知道錯誤邂逅 – Ravi

+0

@Ravi不容易看到,但他想要最昂貴的Jhon,最昂貴的Paul 2和最昂貴的Ringo。 –

回答

0
SELECT Forename, 
     Surname, 
     Cost 
    FROM 
    (
     SELECT *, 
       ROW_NUMBER() OVER (PARTITION BY Forename ORDER BY Cost DESC) 
       AS rn 
      FROM Table2 
    ) 
WHERE rn = 1; 
+0

您的查詢返回保存的一條記錄 –

2

試試這個

SELECT T.Forename,T.Surname, T.Cost 
    FROM 
    (
     SELECT *, 
       ROW_NUMBER() OVER (PARTITION BY Forename ORDER BY Cost DESC) 
       AS rn 
      FROM Table2 
    ) T 
JOIN Table1 ON Table2.Foreman=Table1.Name 
WHERE T.rn <=Qty; 
+0

謝謝,這個效果很好 –

0

更新和測試:如果它是關於從表2取決於表1獲得最高的性價比數量,然後使用以下:

CREATE TABLE #table1 (name NVARCHAR(100), qty INT); 
CREATE TABLE #table2 (forename NVARCHAR(100), surname NVARCHAR(100), cost INT); 

INSERT INTO #table1 VALUES 
('John', 1), 
('Paul', 2), 
('Ringo', 1); 

INSERT INTO #table2 VALUES 
('John', 'Smith', 123), 
('John', 'Jones', 815), 
('Paul', 'Smith', 273), 
('Paul', 'Jones', 297), 
('Ringo', 'Smith', 755), 
('Ringo', 'Jones', 334); 

WITH DATA AS (
SELECT t2.forename, t2.surname, t2.cost, t1.qty, 
rn = ROW_NUMBER() OVER (PARTITION BY t1.name ORDER BY t2.cost DESC) 
FROM 
    #table1 t1 
    INNER JOIN #table2 t2 ON t1.name = t2.forename 
) 
SELECT d.forename, d.surname, d.cost 
    FROM 
DATA d 
WHERE d.rn <= d.qty 
+0

謝謝,這個效果很好 –

0
create table #table1(name varchar(100), qty int) 
create table #table2 (forename varchar(100), surname varchar(100), cost int) 

insert into #table1 values 
('John',1), 
('Paul',2), 
('Ringo',1) 

insert into #table2 values 
('John' ,  'Smith'  , 123), 
('John' , 'Jones' , 815) , 
('Paul' ,  'Smith' , 273), 
('Paul' ,  'Jones' , 297), 
('Ringo' ,  'Smith' , 755), 
('Ringo' ,  'Jones' , 334) 

select * from 
#table1 t1 cross apply 
    (select top (t1.qty) * from #table2 t2 where t1.name = t2.forename order by t2.cost desc) t 
+0

謝謝Shishir,這個效果很好 - 非常簡潔。 –