日期:2014-05-17  浏览次数:20489 次

疑难求解
本帖最后由 dahuatttt 于 2013-04-24 00:24:39 编辑
表结构如下

主表 (PID为主键)
PID Data...
1  X
2  X
3  X
...


副表 (ID为主键,PID为主表的主键)
ID PID Data...
1  1   A
2  1   B
3  1   C
4  2   D
5  2   E
6  3   F
7  3   G
...


目前手中接到一个临时表如下

临时表 (PID就是主表中的PID)
PID Pos
1   2
2   2
3   1

Pos代表的意思是 在副表中指定PID的对应数据的哪一条.(不理解的请往下看示例)

我所希望的结果是:
当接到了一个临时表后(如上那个临时表),抽取pos位置的数据,抽得结果应该如下:

PID Pos ID Data...
1   2   2  B     (因为PID为1的数据有3条,对应数据A,B,C,而pos=2就是B)
2   2   5  E     (因为PID为2的数据有2条,对应数据D,E,而pos=2就是E)
3   1   7  F     (因为PID为3的数据有2条,对应数据F,G,而pos=1就是F)


谢谢!

-----------
我原本考虑 top 1 { [top (pos) order by id]order by 倒序 }
但是貌似很不容易做

另: 存储过程内最好不要用游标

------解决方案--------------------

create table 副表
(ID int, PID int, Data varchar(5))

insert into 副表
select 1, 1, 'A' union all
select 2, 1, 'B' union all
select 3, 1, 'C' union all
select 4, 2, 'D' union all
select 5, 2, 'E' union all
select 6, 3, 'F' union all
select 7, 3, 'G'


create table 临时表
(PID int, Pos int)

insert into 临时表
select 1, 2 union all
select 2, 2 union all
select 3, 1


select t.PID,t.Pos,f.ID,f.Data
 from (select ID,PID,Data,
              row_number() over(partition by PID order by ID) 'rn' from 副表) f
 inner join 临时表 t on f.PID=t.PID and f.rn=t.Pos

/*
PID         Pos         ID          Data
----------- ----------- ----------- -----
1           2           2           B
2           2           5           E
3           1           6           F

(3 row(s) affected)
*/