下表包含活动及其任务:
TASK_ID | TASK_NAME | ACT_ID
========+===========+=======
1000 | A | 300
1001 | B | 300
1002 | C | 300
1003 | A | 400
1004 | D | 400
1005 | B | 500
1006 | C | 500
1007 | D | 500
1008 | A | 600
我需要一个SQL查询,它将以关键形式表示活动及其第一和第二个任务。结果应如下所示:
ACT_ID | Task1st | Task2nd
=======+=========+========
300 | A | B
400 | A | D
500 | B | C
600 | A | NULL
答案 0 :(得分:1)
使用以下带有数据透视的查询
select * from
(
select act_id,task_name,rn from
(
select distinct act_id,task_name,row_number() over (partition by act_id order by act_id) rn from table1
) where rn<=2
)
pivot
(
min(task_name) as task for rn in ( 1 ,2 )
)
order by act_id
答案 1 :(得分:0)
SELECT a.ACT_ID, a.TASK_NAME, b.TASK_NAME
FROM activities a
LEFT JOIN activities b
ON ( a.ACT_ID = b.ACT_ID
AND b.TASK_ID > a.TASK_ID
AND NOT EXISTS ( SELECT 'y'
FROM activities b2
WHERE b2.ACT_ID = b.ACT_ID
AND b2.TASK_ID > a.TASK_ID
AND b2.TASK_ID < b.TASK_ID
)
)
WHERE NOT EXISTS ( SELECT 'x'
FROM activities a2
WHERE a2.ACT_ID = a.ACT_ID
AND a2.TASK_ID < a.TASK_ID
)
如果你需要一个ansi-sql查询可以尝试这个。 附:我没有尝试过数据让我知道它是否有效。