Joining 2 tables while getting the 90th percentile of one table's values

时间:2015-06-30 13:26:47

标签: sql oracle join nested-queries percentile

I have three tables to deal with. These are the sample tables.

enter image description here

I want to get the 90th percentile of each 'operation' in STTR table based on the data in 'value' column. And that also i want only during a time duration. For that requirement i have written this query.

select DISTINCT STTR.OPERATION , 
        PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY STTR.VAL ASC)
        OVER (PARTITION BY STTR.OPERATION) 
         as "90th Percentile"
        from STTR
 WHERE STTR.TIME > (SELECT EXE.START FROM EXE WHERE EXE.ID = 1001) 
 AND
 STTR.TIME < (SELECT EXE.END FROM EXE WHERE EXE.ID = 1001)

This gives me a result with list of operations and their 90th percentile. Like this enter image description here

Now i want to add the columns of the TSS table also into this result and get this kind of result. enter image description here

I tried joining the two tables but then when i added the percentile calculating part with the where clauses it gave me sql errors.

ORA-00913: too many values
00913. 00000 -  "too many values"
*Cause:    
*Action:
Error at Line: 12 Column: 10

This is the method i tired.

SELECT  TSS.ID,
        TSS.STEP,
        TSS.VAL1,
        TSS.VAL2,
        TSS.VAL3,
        (select DISTINCT STTR.OPERATION , PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY STTR.VAL ASC)
        OVER (PARTITION BY STTR.OPERATION) 
         as "90th Percentile"
        from STTR
       WHERE STTR.TIME > (SELECT EXE.START FROM EXE WHERE EXE.ID = 1001) 
 AND
 STTR.TIME < (SELECT EXE.END FROM EXE WHERE EXE.ID = 1001))
      as Percentile                  
FROM TSS
JOIN STTR on STTR.OPERATION = TSS.STEP
WHERE TSS.ID = 1001;

Is this result possible to achieve if so could you guide me through how to achieve it.

2 个答案:

答案 0 :(得分:1)

尝试此查询,它为您的示例提供了所需的输出。

select distinct sttr.operation, tss.val1, tss.val2, tss.val3,
    percentile_disc(0.9) within group (order by sttr.val asc) 
      over (partition by sttr.operation) as "90th Percentile"
  from sttr 
    join exe on exe.tstart < sttr.time and sttr.time < exe.tend
    join tss on sttr.operation = tss.step
  where exe.id = 1001 
  order by operation

SQLFiddle

我重命名了列名称&#34; start&#34;和&#34;结束&#34; to&#34; tstart&#34;,&#34; tend&#34 ;,因为这些是Oracle保留字。

答案 1 :(得分:0)

The error is because you cannot select 2 columns in the select subquery. Try this by moving the subquery to the from clause:

SELECT  TSS.ID,
        TSS.STEP,
        TSS.VAL1,
        TSS.VAL2,
        TSS.VAL3,
        t2.operation, 
        t2.percentile
FROM TSS, 
(select DISTINCT STTR.OPERATION , PERCENTILE_DISC(0.9), 
WITHIN GROUP (ORDER BY STTR.VAL ASC)
        OVER (PARTITION BY STTR.OPERATION) 
         as percentile
        from STTR) t2
JOIN STTR on t2.OPERATION = TSS.STEP
WHERE TSS.ID = 1001;