简体   繁体   English

从Oracle表中得出具有多个条件的结果

[英]Concetating results from Oracle table with several criterias

This is a tough one. 这是困难的一个。 I've read about concatating values from multible rows in a table, but can't find anything on how to go about the task set before me. 我已经读过关于如何从表中的多个行合并值的信息,但找不到关于如何处理摆在我面前的任务集的任何信息。 I'm not an oracle-man, and untill now have only made simple select queries, so I'm at a loss here. 我不是一个Oracle专家,直到现在只进行了简单的选择查询,所以我在这里很茫然。

In a huge oracle database table (severel hundred millions of rows) containing laboratory results, I need to select information on specific requisitions, that meet a specific criteria. 在一个包含实验室结果的巨大的oracle数据库表(几亿行)中,我需要选择满足特定条件的特定请购信息。

Criteria: For the same ReqNo, Analysis AB and C must be present with an answer, if they are, any instance of the answer to analysis X, Y or Z should be selected 准则:对于相同的需求编号,必须在分析AB和C中提供答案,如果存在,则应选择分析X,Y或Z的任何答案实例

Table contents: 表内容:

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

Desired result: 所需结果:

ReqNo   A   B   C   X   Y   Z
1      7    14  18  250     
3      8    16  20          100
5      6    15  22  300 108 88

leaving out ReqNo 2 and 4, since they don't meet the A/B/C criteria. 忽略了要求2和4,因为它们不符合A / B / C标准。

Is that even possible? 那有可能吗?

You may first filter the records that have all 3 (A,B and C) and then use PIVOT to convert them to columns for those which satisfy the criteria. 您可以首先过滤所有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;

Demo 演示版

I would just use conditional aggregation: 我只会使用条件聚合:

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 ;

Given that you don't seem to have duplicates, you can simplify the having to: 既然你似乎并不有重复,可以简化having到:

having sum(case when Ana in ('A', 'B', 'C') then 1 else 0 end) = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM