sql只从第二个表中选择前3行

时间:2014-07-02 20:36:41

标签: sql oracle

我只需要来自子表的3条记录。

CREATE TABLE project
    (prj_code int , prj_name varchar(255) );


CREATE TABLE task
    (id int , prj_code int, task_name varchar(255) );

INSERT INTO project VALUES (1,'myproj1');    
INSERT INTO project VALUES (2,'myproj2');

INSERT INTO task VALUES (1,1,'testing');
INSERT INTO task VALUES (2,1,'prod');
INSERT INTO task VALUES (3,1,'prod2');
INSERT INTO task VALUES (4,1,'testing2');

INSERT INTO task VALUES (5,2,'mytask1');
INSERT INTO task VALUES (6,2,'mytask2');

Please see the fiddle

修改

想要透视表以检索每个项目的列中的3个较小任务ID

2 个答案:

答案 0 :(得分:4)

这段代码可以解决问题。您需要使用RANK选择3个smallests ID,然后选择数据透视表:

WITH tasks AS (
select 
   A.prj_code,
   prj_name,
   RANK() OVER (PARTITION BY A.PRJ_CODE ORDER BY ID ) RANK, 
   ID, 
   TASK_NAME
from task A
inner join project B
   on A.PRJ_CODE = B.PRJ_CODE
order by A.prj_code)


select PRJ_CODE, prj_name, sum(T1) T1, sum(T2) T2, sum(T3) T3
from tasks A
PIVOT (max(ID) for RANK IN ('1' as T1 ,'2' as T2 ,'3' as T3 )) B
GROUP BY PRJ_CODE, prj_name

OR

使用下面的代码来创建任务名称

select PRJ_CODE, prj_name, max(T1) T1, max(T2) T2, max(T3) T3
from tasks A
PIVOT (max(TASK_NAME) for RANK IN ('1' as T1 ,'2' as T2 ,'3' as T3 )) B
GROUP BY PRJ_CODE, prj_name

SQLFiddle

答案 1 :(得分:0)

这是一个可怕的解决方案,但我认为它说明了实现这一目标的一种方法。我不承担任何转动功能,不知道您正在运行的Oracle版本。

with tasks as (
  select
    a.prj_code, a.prj_name,
    b.id, b.task_name,
    row_number() over (partition by a.prj_code order by b.id) as rn
  from
    project a
    join task b on
      a.prj_code = b.prj_code
), pivotdata as (
  select
    prj_code, prj_name,
    case when rn = 1 then task_name end as task_1,
    case when rn = 2 then task_name end as task_2,
    case when rn = 3 then task_name end as task_3
  from tasks
)
select
  prj_code, prj_name,
  max (task_1) as task_1, max (task_2) as task_2,
  max (task_3) as task_3
from pivotdata
group by
  prj_code, prj_name

输出:

Prj Code   Prj Name    Task 1   Task 2  Task 3
1          myproj1     testing  prod    prod2
2          myproj2     mytask1  mytask2