这是一个艰难的过程。我已经读过关于如何从表中的多个行合并值的信息,但找不到关于如何处理摆在我面前的任务集的任何信息。 我不是一个Oracle专家,直到现在只进行简单的选择查询,所以我在这里茫然。
在包含实验室结果的巨大oracle数据库表(几亿行)中,我需要选择符合特定条件的特定请购信息。
条件:对于相同的ReqNo,分析A B和C必须与答案一起出现,如果存在,则应选择分析X,Y或Z的答案的任何实例
表内容:
ReqNo Ana Answer
1 A 7
1 B 14
1 C 18
1 X 250
2 A 8
2 X 35
2 Y 125
3 A 8
3 B 16
3 C 20
3 Z 100
4 X 115
4 Y 355
5 A 6
5 B 15
5 C 22
5 X 300
5 Y 108
5 C 88
所需结果:
ReqNo A B C X Y Z
1 7 14 18 250
3 8 16 20 100
5 6 15 22 300 108 88
省去了第2号和第4号要求,因为它们不符合A / B / C标准。
那有可能吗?
答案 0 :(得分:0)
您可以先过滤所有3个记录(A,B和C),然后使用PIVOT
将其转换为满足条件的列。
with req
AS
(
select reqno from t where ana IN ('A','B','C')
GROUP BY reqno HAVING
count(DISTINCT ana) = 3
)
select * FROM
(
select * from t where
exists ( select 1 from req r where t.reqno = r.reqno )
)
PIVOT(
min(answer) for ana in ('A' as A, 'B' as B, 'C' as C,
'X' as X, 'Y' as Y, 'Z' as Z)
) ORDER BY reqno;
答案 1 :(得分:0)
我只会使用条件聚合:
select reqno,
max(case when Ana = 'A' then Answer end) as a,
max(case when Ana = 'B' then Answer end) as b,
max(case when Ana = 'C' then Answer end) as c,
max(case when Ana = 'X' then Answer end) as x,
max(case when Ana = 'Y' then Answer end) as y,
max(case when Ana = 'Z' then Answer end) as z
from t
group by reqno
having sum(case when Ana = 'A' then 1 else 0 end) > 0 and
sum(case when Ana = 'B' then 1 else 0 end) > 0 and
sum(case when Ana = 'C' then 1 else 0 end) > 0 ;
鉴于您似乎没有重复项,可以将having
简化为:
having sum(case when Ana in ('A', 'B', 'C') then 1 else 0 end) = 3