如果我有几个表,如下所示
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
我希望构造一个查询,以便每个子集从Table2返回的数量由Table2.Cost排序并受Table1.Qty限制,返回类似于:
Results
-----------------------------
Forename Surname Cost
-----------------------------
John Jones 815
Paul Jones 297
Paul Smith 273
Ringo Smith 755
有办法做到这一点吗?
答案 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;
答案 1 :(得分:0)
SELECT Forename,
Surname,
Cost
FROM
(
SELECT *,
ROW_NUMBER() OVER ( PARTITION BY Forename ORDER BY Cost DESC )
AS rn
FROM Table2
)
WHERE rn = 1;
答案 2 :(得分:0)
Updated and Tested: If it's about getting the highest cost from Table 2 depending upon Qty from Table 1, then use the following:
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
答案 3 :(得分: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