Pivot query help
need help on creating pivot query
SELECT * FROM TEST1
----------------
VALUE OF PERSON COMPUTERNAME
COMP1 ABC 3
COMP2 ABC 5
COMP1 CAD 3
COMP3 CAD 5
COMP2 TES 1
COMP1 TES 5
COMP3 ABC 2
myQuery
----------------------------
Select the link null, label, value1 COUNT (VALUE)
from 'test1 '.
CONTROL group PER PERSON
Results
---------
Link label value1
- ABC 3
- CAD 2
- TES 2
My requirement
---------------
can we have something like that out using the concept of pivot? If so can you share an example query pls.
Link label value1
-ABC ORDI1, COMP2, COMP3
-CAD COMP1, COMP2
-YOUR ORDI1, COMP3
Hello
Subhash C-Oracle wrote:
need help on creating pivot query
SELECT * FROM TEST1
----------------
VALUE OF PERSON COMPUTERNAME
COMP1 ABC 3
COMP2 ABC 5
COMP1 CAD 3
COMP3 CAD 5
COMP2 TES 1
COMP1 TES 5
COMP3 ABC 2
myQuery
----------------------------
Select the link null, label, value1 COUNT (VALUE)
from 'test1 '.
CONTROL group PER PERSON
Results
---------
Link label value1
- ABC 3
- CAD 2
- TES 2
My requirement
---------------
can we have something like that out using the concept of pivot? If so can you share an example query pls.
Link label value1
-ABC ORDI1, COMP2, COMP3
-CAD COMP1, COMP2
-YOUR ORDI1, COMP3
This sounds like a job for LISTAGG:
SELECT NULL AS link
label
LISTAGG (comp_name, ',')
THE Group (ORDER BY ComputerName) AS value1
OF test1
GROUP BY label
;
If you would care to post CREATE TABLE and INSERT statements for your sample data, then I could test it.
Are you sure that the results you posted are what you want from data provided?
Is of the order of the elements in a significant list? In other words, when you say you want to get the results:
COMP1, COMP2
you'd be just as happy with
ORDI1, COMP2
? If the order is important, explains what this order.
Tags: Database
Similar Questions
-
Hi all
I wrote a pivot query but it is not giving me the expected output.
with test as ( select 'outgoing' type_of_call, 'local' sub_type_call, '1sec' pulse, 0.3 call_charge from dual union all select 'outgoing' type_of_call, 'STD' sub_type_call, '2sec' pulse, 1.5 call_charge from dual union all select 'outgoing' type_of_call, 'ISD' sub_type_call, '1sec' pulse, 4 call_charge from dual union all select 'SMS' type_of_call, 'local' sub_type_call, '1' pulse, 0.5 call_charge from dual union all select 'SMS' type_of_call, 'STD' sub_type_call, '1' pulse, 1 call_charge from dual union all select 'SMS' type_of_call, 'ISD' sub_type_call, '1' pulse, 3 call_charge from dual ) select * from test pivot(count(type_of_call) for (sub_type_call) in ('local','STD','ISD') ); O/P should look like Type_of_call pulse_local charge_local Pulse_STD charge_STD pulse_ISD charge_isd outgoing 1sec 0.3 2sec 1.5 1sec 4 SMS 1 0.5 1 1 1 3
Is there something that I am missing in the query?
Thank you
SID
SQL> with test as ( select 'outgoing' type_of_call, 'local' sub_ty, '1sec' pulse, 0.3 call_charge from dual union all select 'outgoing' type_of_call, 'STD' sub_ty, '2sec' pulse, 1.5 call_charge from dual union all select 'outgoing' type_of_call, 'ISD' sub_ty, '1sec' pulse, 4 call_charge from dual union all select 'SMS' type_of_call, 'local' sub_ty, '1' pulse, 0.5 call_charge from dual union all select 'SMS' type_of_call, 'STD' sub_ty, '1' pulse, 1 call_charge from dual union all select 'SMS' type_of_call, 'ISD' sub_ty, '1' pulse, 3 call_charge from dual ) select * from test pivot(max(CALL_CHARGE) as CALL_CHARGE, max(pulse) as pulse for (sub_ty) in ('local' as local,'STD' as std,'ISD' as isd) ) order by type_of_call desc 2 3 4 5 6 7 8 9 10 11 12 13 / TYPE_OF_ LOCAL_CALL_CHARGE LOCA STD_CALL_CHARGE STD_ ISD_CALL_CHARGE ISD_ -------- ----------------- ---- --------------- ---- --------------- ---- outgoing .3 1sec 1.5 2sec 4 1sec SMS .5 1 1 1 3 1
-
I'm new to PIVOT queries. I was making reference to the discussion that follows, but ran into a problem.
When I added the XML to format data, I started to have NULL values rather than what I was looking for.
WITH (AS PIVOT_DATA)
SELECT * FROM)
SELECT THE REGION, FCST_PERIOD, PRIME_PART, FINAL_FORECAST
OF XYZ WHERE FCST_PERIOD > = last_day (trunc (sysdate)) + 1 and FCST_PERIOD < = last_day (add_months(sysdate,12)) AND PRIME_PART IN ('BLAH')
)
PIVOT XML (SUM (FINAL_FORECAST) FOR FCST_PERIOD IN (SELECT DISTINCT FCST_PERIOD OF XYZ))
)
SELECT PRIME_PART, REGION,
EXTRACTVALUE(FCST_PERIOD_XML,'/PIVOTSET/ITEM[1]/COLUMN[2]') FCST_PERIOD1,
EXTRACTVALUE(FCST_PERIOD_XML,'/PIVOTSET/ITEM[2]/COLUMN[2]') FCST_PERIOD2,
EXTRACTVALUE(FCST_PERIOD_XML,'/PIVOTSET/ITEM[3]/COLUMN[2]') FCST_PERIOD3
OF PIVOT_DATA;
RESULTS IN:
PRIME_PART REGION FCST_PERIOD1 FCST_PERIOD2 FCST_PERIOD3 BLA MIDWEST (NULL) (NULL) (NULL) BLA WEST-NV (NULL) (NULL) (NULL) BLA SOUTH-EAST (NULL) (NULL) (NULL) BLA WEST-CA (NULL) (NULL) (NULL) BLA SOUTHWEST (NULL) (NULL) (NULL) BLA EAST (NULL) (NULL) (NULL) The second part of my question is how would I do a group when you use a pivot query. When I finished, I've has several parts and would like to group by REGION.
Thank you!
Names of elements and attributes in XML are case-sensitive.
Try with:
EXTRACTVALUE (FCST_PERIOD_XML, ' / PivotSet/item [1] /column [2]') FCST_PERIOD1
There is also a good chance that EXTRACTVALUE is frowned upon in your version. Instead, use XMLQuery or XMLTable.
That being said, using XML PIVOT just to grind it later into a number known columns is pretty useless.
The same can be achieved much more efficiently with regular PIVOT operator (and if necessary analytical function).
Post some examples of data in the table of your database and your final result expected to get useful assistance.
-
I have a query in Oracle 11:
Resultselect to_char(da,'DY-DD') days from ( select rownum -1 + to_date('2012-10-15','yyyy-mm-dd') da, l from (select level l from dual connect by level <= to_date('2012-10-21','yyyy-mm-dd') - to_date('2012-10-15','yyyy-mm-dd')+1) order by 1)
What I need which is present in a row instead of a column:"DAYS" MON-15 TUE-16 WED-17 THU-18 FRI-19 SAT-20 SUN-21
This should be done with pivot requests? Any suggestion please!MON-15 TUE-16 WED-17 THU-18 FRI-19 SAT-20 SUN-21
Thanks in advance.Hello
user564819 wrote:
I need in 7 different columns.
Oracle version is 11.2.0.1.0. Could you give an example of how to do this with pivot query?Here's one way:
WITH all_days AS ( SELECT LEVEL AS n , TO_CHAR ( TO_DATE ('2012-10-15','yyyy-mm-dd') + LEVEL - 1 , 'DY-DD' ) AS dy_dd FROM dual CONNECT BY LEVEL <= TO_DATE ('2012-10-21','yyyy-mm-dd') + 1 - TO_DATE ('2012-10-15','yyyy-mm-dd') ) SELECT * FROM all_days PIVOT ( MIN (dy_dd) FOR n IN ( 1 AS col_1 , 2 AS col_2 , 3 AS col_3 , 4 AS col_4 , 5 AS col_5 , 6 AS col_6 , 7 AS col_7 , 8 AS col_8 , 9 AS col_9 , 10 AS col_10 ) ) ;
This always displays exactly 10 columns.
If the subquery produces less than 10 dates, then the last columns will be NULL.
If the subquery produces more than 10 dates, will be not shown the 11th (and later versions).There is nothing special about the number 10; You can have any number of columns you want. The number of columns and their names is fixed when you write the query, regardless of what is in the subquery. If you want a dynamic number of columns, or names derived from data, see {message identifier: = 3527823}
-
Getting counties and divide by the sum in a single Pivot query
Hello
I have a pivot query that gives counties of all codes. I have also separated the number with the total in the same query.
Now, the output should have the counts / divided into sum multiplied by 100. Basically, the percentage.e.g col1 col2 col3 error_1 05-Jun-2012 parts error_1 05_june_2012 parts error_1 04_june_2012 consumables error_2 04_june_2012 consumables error_3 03_june_2012 parts . . .
output will be something like
Any suggestions please?error June-2012 May-2012 Feb-2012 .... headers error_1 60% 0 % 0% error_2 20% 0 0% error_3 20% 0% 0%
Thank you
Sunwith t1 as (select 'error_1' col1,trunc(sysdate) - 1 col2 from dual union all select 'error_1',trunc(sysdate) - 1 from dual union all select 'error_1',trunc(sysdate) + 30 from dual union all select 'error_2',trunc(sysdate) + 31 from dual union all select 'error_3',trunc(sysdate) - 2 from dual union all select 'error_3',trunc(sysdate) + 30 from dual union all select 'error_1',trunc(sysdate) - 3 from dual union all select 'error_2',trunc(sysdate) - 2 from dual union all select 'error_3',trunc(sysdate) + 30 from dual union all select 'error_4',trunc(sysdate) - 6 from dual ) select col1, count(case to_char(col2,'mon') when 'jul' then 1 end) one, 100 * ratio_to_report(count(case to_char(col2,'mon') when 'jul' then 1 end)) over () x, count(case to_char(col2,'mon') when 'jun' then 1 end) two, 100 * ratio_to_report(count(case to_char(col2,'mon') when 'jun' then 1 end)) over () y from t1 group by col1 order by col1
Concerning
Etbin
Edited by: Etbin on 8.6.2012 14:15
used month next to keep English and slovene "LUN" same ;) -
I have a requirement as below-
The output I want as below.
I wrote a query as below with hard-code the code produced.EMP_ID LAPTOP DESK LAPTOP LCD MONITOR ROUTER ------------------------------------------------------------------------------------------ 100 Y Y Y Y 101 Y N Y N 102 N Y N N -----------------------------------------------------------------------------------------
I want a solution without Hardcoding code product, because if we need to introduce a new product in the product table, then the output will be fit dynamically...SELECT EMP_ID, NVL(MAX(DECODE(PROD_ID,10,'Y',NULL)),'N') LAPTOP, NVL(MAX(DECODE(PROD_ID,11,'Y',NULL)),'N') DESK_LAPTOP, NVL(MAX(DECODE(PROD_ID,12,'Y',NULL)),'N') LCD_MONITOR, NVL(MAX(DECODE(PROD_ID,13,'Y',NULL)),'N') ROUTER FROM XX_EMP a GROUP BY EMP_ID;
Is it possible to write the query like this?
Is my version of DB - Oracle 10 g
Table creation script-
CREATE TABLE XX_EMP ( EMP_ID NUMBER, PROD_ID NUMBER, SALE_DT DATE ); INSERT INTO XX_EMP VALUES(100,10,sysdate-15); INSERT INTO XX_EMP VALUES(100,11,sysdate-14); INSERT INTO XX_EMP VALUES(100,12,sysdate-14); INSERT INTO XX_EMP VALUES(100,13,sysdate-13); INSERT INTO XX_EMP VALUES(101,11,sysdate-11); INSERT INTO XX_EMP VALUES(101,13,sysdate-10); INSERT INTO XX_EMP VALUES(102,12,sysdate-10); COMMIT; CREATE TABLE XX_PRODUCT(PROD_ID NUMBER, PROD_DES VARCHAR2(50) ); INSERT INTO XX_PRODUCT VALUES(10,'LAPTOP'); INSERT INTO XX_PRODUCT VALUES(11,'DESK LAPTOP'); INSERT INTO XX_PRODUCT VALUES(12,'LCD MONITOR'); INSERT INTO XX_PRODUCT VALUES(13,'ROUTER'); COMMIT;
Hello
See this thread for more options:
Re: County report and the sum of the number of rows by multiple columnsIt seems that the aggregation of the chain might be the best for this work.
For example:
I guess you don't want to view the whole xx_emp table in all reports. In the first auxiliary request, emp_summary, below I've limited the output lines with the sale_dt in the last 30 days. You can change this to anything else, or omit the WHERE all clause if you do not want to include the entire table.
I assume that you will not necessarily interested in the whole xx_product. In the second auxiliary request, product_summary, I've limited the output to products that appear effectively in emp_summary. Again, you can use any conditions you want, or include all the lines.
The main request is the UNION of 3 games: 2 produce header lines, and the third produces the bulk of the production. Note that (as far as Oracle is concerned) there are only 2 columns in the output. The last of them will be foramatted to resemble a variable number of columns.VARIABLE column_width NUMBER EXEC :column_width := 12; SET PAGESIZE 0 WITH emp_summary AS ( SELECT emp_id, prod_id FROM xx_emp WHERE sale_dt >= TRUNC (SYSDATE - 30) -- or whatever GROUP BY emp_id, prod_id ) , product_summary AS ( SELECT prod_id , SUBSTR (prod_des, 1, :column_width) AS short_prod_des , ROW_NUMBER () OVER (ORDER BY prod_id) AS r_num FROM xx_product WHERE prod_id IN ( SELECT prod_id FROM emp_summary ) ) -- -- ===== First Header Line: Product Names ===== -- SELECT NULL AS emp_id , REPLACE ( SYS_CONNECT_BY_PATH ( LPAD ( short_prod_des , :column_width ) , '~' ) , '~' , ' ' ) AS txt FROM product_summary WHERE CONNECT_BY_ISLEAF = 1 START WITH r_num = 1 CONNECT BY r_num = PRIOR r_num + 1 -- UNION ALL -- ===== Second Header Line: Hyphens ===== -- SELECT NULL AS emp_id , SYS_CONNECT_BY_PATH ( LPAD ( '-' , :column_width , '-' ) , ' ' ) AS txt FROM product_summary WHERE CONNECT_BY_ISLEAF = 1 START WITH r_num = 1 CONNECT BY r_num = PRIOR r_num + 1 -- UNION ALL -- ===== Body of Report ===== -- SELECT e.emp_id , REPLACE ( SYS_CONNECT_BY_PATH ( LPAD ( NVL2 ( e.prod_id , 'Y' , 'N' ) , :column_width ) , '~' ) , '~' , ' ' ) AS txt FROM product_summary p LEFT OUTER JOIN emp_summary e PARTITION BY (e.emp_id) ON p.prod_id = e.prod_id WHERE CONNECT_BY_ISLEAF = 1 START WITH p.r_num = 1 CONNECT BY p.r_num = PRIOR p.r_num + 1 AND e.emp_id = PRIOR e.emp_id -- -- ===== Common ORDER BY Clause ===== -- ORDER BY emp_id NULLS FIRST , txt ;
Output:
` LAPTOP DESK LAPTOP LCD MONITOR ROUTER ------------ ------------ ------------ ------------ 100 Y Y Y Y 101 N Y N Y 102 N N Y N
There are a few things you might want to change.
For example, if the first product_name is: characters column_width, the ORDER BY clause will put hyphens, first. Which can be fixed by putting the UNION in a subquery, so that you can ORDER BY columns that do not appear in the output.You could also include all product_des, dividing each item into pieces of no. more: column_width characters. I'll leave that as an exercise.
Published by: Frank Kulash, April 12, 2011 17:49
Example of grouping of extra chain -
11G Pivot query with Oracle EBS
Hi all
We try to use the request function pivot 11G with Oracle E-Business Suite data. We have a database 11G installed with our Oracle APEX. We do not seem to get the pivot function to work. In short, anyone would be able to see the glaring errors in our syntax. I am not sure that it is possible to provide data of test so...
We try to have with the period column headers names SEP-08 OCT-08 NOV-08, with rows of segment2 007751 and accounted_dr as DataSet.
When we run the sql code we get an error ORA-00904: "PERIOD_NAME": invalid identifier.
Any help or idea would be greatly appreciated.
Select * from)
Select segment2, accounted_dr, period_name
gl_je_lines a, gl_code_combinations b
where b.code_combination_id = a.code_combination_id
and segment2 = "007751")
Pivot
(
Sum (accounted_dr)
for period_name ("SEP-08', ' 08 OCT ', ' NOV-08'")
)
Segment2 group, period_namelilhelp wrote:
Hi all
We try to use the request function pivot 11G with Oracle E-Business Suite data. We have a database 11G installed with our Oracle APEX. We do not seem to get the pivot function to work. In short, anyone would be able to see the glaring errors in our syntax. I am not sure that it is possible to provide test dataWhy not?
>We try to have with the period column headers names SEP-08 OCT-08 NOV-08, with rows of segment2 007751 and accounted_dr as DataSet.
When we run the sql code we get an error ORA-00904: "PERIOD_NAME": invalid identifier.Any help or idea would be greatly appreciated.
Select * from)
Select segment2, accounted_dr, period_name
gl_je_lines a, gl_code_combinations b
where b.code_combination_id = a.code_combination_id
and segment2 = "007751")
Pivot
(
Sum (accounted_dr)
for period_name ("SEP-08', ' 08 OCT ', ' NOV-08'")
)
Segment2 group, period_nameDo not use GROUP BY. When you use PIVOT, the group is involved with what is in the PIVOT clause and which is not.
Try this:select * from ( select segment2 , accounted_dr , period_name from gl_je_lines a , gl_code_combinations b where b.code_combination_id = a.code_combination_id and segment2 = '007751' ) pivot ( sum (accounted_dr) for period_name in ('SEP-08','OCT-08','NOV-08') ) ;
which is just your query validated without the GROUP BY clause.
-
Oracle 11g Release 2
Frank Kulash was able to help on this issue yesterday. But I got additional requirements. Details below.
CASE 1:
create table t
(key primary id number,)
supplier_id number,
number of supplier_desc_id
batch number,
date of dt_recv
)
/
Insert into t
values (35405,605,3809,0,TO_DATE('14-JUN-2013','DD-MON-yyyy')
/
Insert into t
values (58543,605,3809,0,TO_DATE('10-DEC-2013','DD-MON-yyyy')
/
Insert into t
values (136793,605,3809,1,TO_DATE('11-NOV-2014','DD-MON-yyyy')
/
Insert into t
values (96510,605,3809,1,TO_DATE('11-JUN-2014','DD-MON-yyyy')
/
Insert into t
values (94222,605,3809,1,TO_DATE('09-MAY-2014','DD-MON-yyyy')
/
Insert into t
values (108229,605,3809,3,TO_DATE('09-SEP-2014','DD-MON-yyyy')
/
Insert into t
values (114585,605,3809,2,TO_DATE('28-OCT-2014','DD-MON-yyyy')
/
commit;
Select * from t;
ID SUPPLIER_ID SUPPLIER_DESC_ID BATCH DT_RECV
---------- ----------- ------------------------ ----------------- -------------
35405 605 3809 0 14 JUNE 2013
58543 605 3809 0 10 DECEMBER 2013
3809 605 136793 1 11 NOVEMBER 2014
96510 605 3809 1 10 JUNE 2014
94222 605 3809 1 9 MAY 2014
108229 605 3809 3 09 - SEP - 2014
114585 605 3809 2 28 OCTOBER 2014
RULE: when there are 2 or more records with batch = 1, return the two most
recent recordings with batch = 1 AND any recording (no matter the batch) that
has a DT_RECV > = only the DT_RECV of the 2nd record most of batch = 1 (June 10, 2014)
96510 10 June 2014 (2nd most active record with batch = 1)
136793 11 November 2014 (more current label with batch = 1)
94222 may 9, 2014 (not interested in this matter, since it is greater than 2 versions)
The results should be:
ID SUPPLIER_ID SUPPLIER_DESC_ID STATUS_ID DT_RECV ---------- ----------- ------------------------ ----------------- ------------- 96510 605 3809 1 10-JUN-2014 136793 605 3809 1 11-NOV-2014 114585 605 3809 2 28-OCT-2014 >= 10-JUN-2014 108229 605 3809 3 09-SEP-2014 >= 10-JUN-2014 This query returns the correct results: WITH got_r_num AS ( SELECT id, supplier_id, supplier_desc_id, status_id, dt_recv , ROW_NUMBER () OVER ( PARTITION BY supplier_id,supplier_desc_id,status_id ORDER BY dt_recv DESC ) AS r_num FROM t ) , got_dt_cutoff AS ( SELECT id, supplier_id, supplier_desc_id, status_id, dt_recv , MIN ( CASE WHEN status_id = 1 AND r_num <= 2 THEN dt_recv END ) OVER (PARTITIN BY supplier_id,supplier_desc_id) AS dt_cutoff FROM got_r_num ) SELECT id, supplier_id, supplier_desc_id, status_id, dt_recv FROM got_dt_cutoff WHERE dt_recv >= dt_cutoff ORDER BY dt_recv ; NOTE: records are grouped by supplier_id/supplier_desc_id
CASE 2:
truncate table t; insert into table t values(45401,801300,4466,0,TO_DATE('21-AUG-2013','DD-MON-YYYY') / insert into table t values(44414,801300,4466,0,TO_DATE('08-AUG-2013','DD-MON-YYYY') / commit ; select * from t; CONTENT_ID SUPPLIER_ID SUPPLIER_CONTENT_DESC_ID CONTENT_STATUS_ID RECEIVE_DATE ---------- ----------- ------------------------ ----------------- ------------ 451 801300 4466 0 21-AUG-2013 44414 801300 4466 0 08-AUG-2013 801300 4466 0 08-AUG-2013
RULE: when there is no batch = 1, then return all rows
The query above does not work for this case.
CASE 3:
truncate table t; insert into table t values(29887,609051,1781,0,TO_DATE('19-APR-2013','DD-MON-YYYY') / insert into table t values(33623,609051,1781,0,TO_DATE('24-MAY-2013','DD-MON-YYYY') / insert into table t values(45477,609051,1781,0,TO_DATE('22-AUG-2013','DD-MON-YYYY') / insert into table t values(54013,609051,1781,1,TO_DATE('22-OCT-2013','DD-MON-YYYY') / commit; select * from t; CONTENT_ID SUPPLIER_ID SUPPLIER_CONTENT_DESC_ID CONTENT_STATUS_ID RECEIVE_DATE ---------- ----------- ------------------------ ----------------- ------------- 29887 609051 1781 0 19-APR-2013 33623 609051 1781 0 24-MAY-2013 45477 609051 1781 0 22-AUG-2013 54013 609051 1781 1 22-OCT-2013
RULE: When there is only to record with batch = 1, return all rows
The query above does not work for this case.
Hello
orclrunner wrote:
Oracle 11g Release 2
Frank Kulash was able to help on this issue yesterday. But I got additional requirements. Details below.
CASE 1:
create table t
(key primary id number,)
supplier_id number,
number of supplier_desc_id
batch number,
date of dt_recv
)
/
Insert into t
values (35405,605,3809,0,TO_DATE('14-JUN-2013','DD-MON-yyyy')
/
Insert into t
values (58543,605,3809,0,TO_DATE('10-DEC-2013','DD-MON-yyyy')
/
Insert into t
values (136793,605,3809,1,TO_DATE('11-NOV-2014','DD-MON-yyyy')
/
Insert into t
values (96510,605,3809,1,TO_DATE('11-JUN-2014','DD-MON-yyyy')
/
Insert into t
values (94222,605,3809,1,TO_DATE('09-MAY-2014','DD-MON-yyyy')
/
Insert into t
values (108229,605,3809,3,TO_DATE('09-SEP-2014','DD-MON-yyyy')
/
Insert into t
values (114585,605,3809,2,TO_DATE('28-OCT-2014','DD-MON-yyyy')
/
commit;
Select * from t;
ID SUPPLIER_ID SUPPLIER_DESC_ID BATCH DT_RECV
---------- ----------- ------------------------ ----------------- -------------
35405 605 3809 0 14 JUNE 2013
58543 605 3809 0 10 DECEMBER 2013
3809 605 136793 1 11 NOVEMBER 2014
96510 605 3809 1 10 JUNE 2014
94222 605 3809 1 9 MAY 2014
108229 605 3809 3 09 - SEP - 2014
114585 605 3809 2 28 OCTOBER 2014
RULE: when there are 2 or more records with batch = 1, return the two most
recent recordings with batch = 1 AND any recording (no matter the batch) that
has a DT_RECV > = only the DT_RECV of the 2nd record most of batch = 1 (June 10, 2014)
96510 10 June 2014 (2nd most active record with batch = 1)
136793 11 November 2014 (more current label with batch = 1)
94222 may 9, 2014 (not interested in this matter, since it is greater than 2 versions)
The results should be:
- ID SUPPLIER_ID SUPPLIER_DESC_ID BATCH DT_RECV
- ---------- ----------- ------------------------ ----------------- -------------
- 96510 605 3809 1 10 JUNE 2014
- 3809 605 136793 1 11 NOVEMBER 2014
- 114585 605 3809 2 28 OCTOBER 2014 > = JUNE 10, 2014
- 108229 605 3809 3 09 - SEP - 2014 > = JUNE 10, 2014
- This query returns the correct results:
- WITH got_r_num AS
- (
- SELECT id, supplier_id, supplier_desc_id, batch, dt_recv
- , ROW_NUMBER () OVER (PARTITION BY supplier_id, supplier_desc_id, batch)
- ORDER BY dt_recv DESC
- ) AS r_num
- T
- )
- got_dt_cutoff AS
- (
- SELECT id, supplier_id, supplier_desc_id, batch, dt_recv
- MIN (CASE
- WHEN batch = 1
- AND r_num<=>=>
- THEN dt_recv
- END
- ) ON (PARTITIN BY supplier_id, supplier_desc_id) AS dt_cutoff
- OF got_r_num
- )
- SELECT id, supplier_id, supplier_desc_id, batch, dt_recv
- OF got_dt_cutoff
- WHERE dt_recv > = dt_cutoff
- ORDER BY dt_recv
- ;
- NOTE: the records are grouped by supplier_id/supplier_desc_id
CASE 2:
- truncate table t;
- insert into table t
- values (45401,801300,4466,0,to_date('21-Aug-2013','DD-mon-YYYY')
- /
- insert into table t
- values (44414,801300,4466,0,to_date('08-Aug-2013','DD-mon-YYYY')
- /
- commit;
- Select * from t;
- CONTENT_ID SUPPLIER_ID SUPPLIER_CONTENT_DESC_ID CONTENT_STATUS_ID RECEIVE_DATE
- ---------- ----------- ------------------------ ----------------- ------------
- 451 801300 4466 0 21 AUGUST 2013
- 44414 801300 4466 0 AUGUST 8, 2013
- 801300 4466 0 AUGUST 8, 2013
RULE: when there is no batch = 1, then return all rows
The query above does not work for this case.
CASE 3:
- truncate table t;
- insert into table t
- values (29887,609051,1781,0,to_date('19-Apr-2013','DD-mon-YYYY')
- /
- insert into table t
- values (33623,609051,1781,0,to_date('24-May-2013','DD-mon-YYYY')
- /
- insert into table t
- values (45477,609051,1781,0,to_date('22-Aug-2013','DD-mon-YYYY')
- /
- insert into table t
- values (54013,609051,1781,1,to_date('22-Oct-2013','DD-mon-YYYY')
- /
- commit;
- Select * from t;
- CONTENT_ID SUPPLIER_ID SUPPLIER_CONTENT_DESC_ID CONTENT_STATUS_ID RECEIVE_DATE
- ---------- ----------- ------------------------ ----------------- -------------
- 29887 609051 1781 0 19 APRIL 2013
- 33623 609051 1781 0 24 MAY 2013
- 45477 609051 1781 0 22 AUGUST 2013
- 54013 609051 1781 1 22 OCTOBER 2013
RULE: When there is only to record with batch = 1, return all rows
The query above does not work for this case.
Want to get answers that work, or is it possible to get responses that cause errors?
Make sure that the INSERT statements you post too much work. Test (and, if necessary, correct) them before posting. All the instructions insert above have errors.
The query above (once you correct the spelling of PARTITION) returns all the lines after a date limit. It's always what you want, only the details of how calculated this date limit changed. In accordance with the new requirements, the closing date must be earlier than the actual lines dt_recv in there are not 2 (or more) with batch = 1 for any combination of (supplier_id, supplier_desc_id). All you have to do is change "r_num".<= 2"="" to="" "r_num="2" ,"="" when="" computing="" dt_cutoff,="" and="" return="" an="" impossiblly="" early="" date="" if="" there="" is="" no="" such="" row. ="" (i="" assume="" that="" dt_recv="" can="" not="" be="">=>
WITH got_r_num AS
(
SELECT id, supplier_id, supplier_desc_id, batch, dt_recv
ROW_NUMBER () OVER (PARTITION BY supplier_id
supplier_desc_id
batch
ORDER BY dt_recv DESC
) AS r_num
T
)
got_dt_cutoff AS
(
SELECT id, supplier_id, supplier_desc_id, batch, dt_recv
, NVL ( MIN (CASE)
WHEN batch = 1
AND = 2 r_num - not <=, as="">=,>
THEN dt_recv
END
) OVER (PARTITION BY supplier_id
supplier_desc_id
)
, TO_DATE ('1', 'J') - first DATE in Oracle
( ) AS dt_cutoff
OF got_r_num
)
SELECT id, supplier_id, supplier_desc_id, batch, dt_recv
OF got_dt_cutoff
WHERE dt_recv > = dt_cutoff
ORDER BY supplier_id
supplier_desc_id
dt_recv
;
If dt_recv can be NULL, it is a bit more complicated, but only a little. Post instructions INSERT (work) and outcomes if you would like to help with this scenario.
-
Dear friends,
Version of DB - 11.1.0.7... , I'm stuck with SQL basics today... need your help...
The slot SQL tells me "cache them locks library" in the database that I will put up as a proactive measure.
I'll be it works via shell script and include the table gv instance_name $ instance ... I'm a little confused as to how a 3rd table "gv$ instance ' can be introduced into the query in order to make the instance_name in the result set...
SELECT * FROM)
SELECT / * + LEADING (a) USE_HASH (u) * /.
instance_name, INST_ID select, blocking_inst_id, blocking_session, username, session_id, sql_id, current_obj #,.
DECODE (sql_opcode, 1, 'CREATE TABLE', 2, 'INSERT') as "order."
Event, mod(P1,16) p1, p2, p3
COUNT (*) totalseconds
, SUM (CASE WHEN wait_class = 'Application' THEN 1 ELSE 0 END) 'Application '.
Of
(SELECT
a.*
, TO_CHAR (CASE WHEN session_state = 'WAITING' THEN ELSE null END p1, '0XXXXXXXXXXXXXXX') p1hex
, TO_CHAR (CASE WHEN session_state = "PENDING" THEN p2 ELSE null END, '0XXXXXXXXXXXXXXX') p2hex
, TO_CHAR (CASE WHEN session_state = "PENDING" THEN ELSE null END p3, '0XXXXXXXXXXXXXXX') p3hex
SGS $ active_session_history one) a
u dba_users
WHERE
a.user_id = u.user_id
AND sample_time BETWEEN sysdate-90 /(24*60) AND sysdate
- AND a test of ('library cache lock', 'library cache pin")
AND event like '% library '.
GROUP BY
INST_ID select, blocking_inst_id, blocking_session, username, session_id, sql_id, current_obj #,.
DECODE (sql_opcode, 1, 'CREATE TABLE', 'INSERT', 2),
event, mod (p1, 16), p2, p3
Having count (*) > 5
ORDER BY
TotalSeconds DESC
, INST_ID select, blocking_session, username, session_id, sql_id, current_obj #, 'Order', event
)
WHERE
ROWNUM < = 20
/
replace
instance_name
by
(select instance_name gv$ instance where INST_ID select = a.inst_id) instance_name
or select... in... a, u, gv$ instance where... and gv$ instance.inst_id (+) = a.inst_id...
-
SQL Query Help (not working not properly)
Hello everyone,
I use JDeveloper 12.1.2.0.0. I do a two-way communication using 3 tables, with links between them (and using schema HR).
In my example, I have something like:
Departments, employees, and the SalaryByJobs (I created this table where it shows a departmentd id, employee id, salary).
Whenever I click on one OR more departments, the employees up-to-date table by putting on the table, employees who belong to the selected department and the salaryByjob to put the jobs of the employees selected on the employees table.
So it's something like this:
The departments selected-> employees selected-> salarybyjbobs of these employees.
My query used (in the view) has the following code:
SELECT Employees.COMMISSION_PCT,
Employees.DEPARTMENT_ID,
Employees.EMAIL,
Employees.EMPLOYEE_ID,
Employees.FIRST_NAME,
Employees.HIRE_DATE,
Employees.JOB_ID,
Employees.LAST_NAME,
Employees.MANAGER_ID,
Employees.PHONE_NUMBER,
Employees.SALARY
Employees EMPLOYEES
WHERE (department_id IN (select * from THE (select cast (in_list(:variavel3) as mytableType) double) a))
Since I use the links, the employees table does not show anything at the beginning, so I added this to my query used to go: OR nvl(:variavel3,0) = 0
But now, whenever I try to select multiple lines, it gives me the invalid numbers and I don't understand why...
It's only one line of code and it is not in the bean.
Can someone help me?
PS - The bean will Department by Department, adds the departments with ',' and for each Department, gets employees who belongs to them.
My best regards,
Frederico Barracha.
The expression NVL (: variavel3, 0) = 0 is not correct. The data type of the return value of the NVL function is considered to be equal to the data type of the argument of 1 (that is, the data type of the variable binding: variavel3). You said that this variable contained a list separated by commas to ID, so the data type of the variable is VARCHAR2. As long as you compare the NVL expression of a number, you get 'Invalid number' exception, because Oracle expects a numeric data type on the left side of the comparison operator.
To avoid the exception "Invalid number", you can modify the expression by using one of the following options:
: variavel3 IS NULL
NVL (: variavel3, ' *') = ' *'
NVL (: variavel3, ' 0') = '0'
Option 1, so the simplest and clearest.
Dimitar
-
I have a request pivot within a region of APEX (pl sql function return sql query) report
declare v_term_pivot varchar2(500); PIVIN LONG; cursor xtoy is SELECT distinct d.JOB FROM emp d; v_query LONG; begin OPEN xtoy; LOOP FETCH xtoy into v_term_pivot; EXIT when xtoy%NOTFOUND; PIVIN:=PIVIN||''''||v_term_pivot||''' "'||substr(v_term_pivot,1,30)||'", '; END LOOP; v_query:='SELECT * FROM (SELECT x.ENAME, x.JOB, x.SAL FROM emp x) PIVOT ( SUM(x.SAL) FOR x.JOB IN ('||substr(PIVIN, 0, length(PIVIN)-1)||') ) order by 1;'; --dbms_output.put_line(v_query); RETURN v_query; end;
Get an error:
Failed to parse the SQL query:
ORA-01748: only here allowed simple column names
Can someone advice how can this be corrected?
I reworked the code to use the scott. EMP table.
I got the SQL Select function resulting and he ran in SQL Developer.
Syntax 1
You must remove aliases for tables of the PIVOT() section.
line 16 and 17 should be
SUM (SAL)
FOR USE IN (...)
Syntax 2
Line 11: you add comma and space (2 characters)
Line 17: you remove only 1 tank
Syntax 3 (problem semi)
Although the APEX works with it, I would abandon the semicolon (;) to the end.
To name the columns, you must create a function that returns the name of the report column.
Again, this must match the columns listed in the SELECT part
reminder of my warning:
Using a "SELECT *" and lack of "ORDER BY" in your cursor will cause you problems. (maybe not now, but it will.)
MK
-
simple query help :)
I have table with date, customer number, salary... Now, I want to extract the total number of client whose salary is between 2000 and 3000 and deposited consistantly for the last 6 months.
Can someone help me with this...user12183668 wrote:
I used your query... its working well... but there are a few County for the date (NTC) which I am less than 6... .and I want to exclude these documents at the level of the query.How can I do this
By encapsulating the query as an interior view, something in this way:
select * from ( select empno ,count(distinct trunc(hiredate,'MM')) cnt from emp where sal between 2000 and 3000 and hiredate >= add_months (trunc(sysdate, 'MM'), -5 ) group by empno ) a where a.cnt = 6;
-
I need help in writing a query. The data that I now contains three columns. The values in the first column have duplicate, and the 2nd column entries. The third is unique. Here is an example of the data that I have today:
Column1 Column2 Column3
Tier1 Group1 1
Tier1 Group1 2
Group level 1 2 3
Tier1 Group2 4
Group level 1 3 5
Level 1 Group 3 6
Expected result:
Column1 Column2 Column3
Tier1 Group1 1
2
2 3 Group
4
3 5 group
6
Thanks for your helpHello
Your front end that can probably not for you.
In SQL * Plus, for example:BREAK ON column1 ON column2 SELECT column1, column2, column3 FROM table_x ORDER BY column3 ;
If you havd do in SQL, here's one way:
SELECT CASE WHEN ROW_NUMBER () OVER ( PARTITION BY column1 ORDER BY column3 ) = 1 THEN column1 END AS col1 , CASE WHEN ROW_NUMBER () OVER ( PARTITION BY column2 ORDER BY column3 ) = 1 THEN column1 , END AS col2 , column3 FROM table_x ORDER BY column3 ;
I hope that answers your question.
If not, post a small example data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and also publish outcomes from these data.
Highlight a few places where the queries above are getting incorrect results and explain, using specific examples, how you get the results of the data provided in these places.
Always tell what version of Oracle you are using.Published by: Frank Kulash, March 21, 2012 16:15
-
calculate the value of the query help
Hi all
Following the script nicely:CREATE TABLE ACCOUNT_LOOCKUP ( SERIAL_ID NUMBER, ACCOUNT_ID NUMBER, ACCOUNT_RATE NUMBER, ACCOUNT_MAX NUMBER ) ALTER TABLE ACCOUNT_LOOCKUP ADD ( CONSTRAINT PK_ACCOUNT_LOOCKUP PRIMARY KEY (SERIAL_ID, ACCOUNT_ID)); Insert into ACCOUNT_LOOCKUP (SERIAL_ID, ACCOUNT_ID, ACCOUNT_RATE, ACCOUNT_MAX) Values (1, 1, 10, 200); Insert into ACCOUNT_LOOCKUP (SERIAL_ID, ACCOUNT_ID, ACCOUNT_RATE, ACCOUNT_MAX) Values (2, 1, 12, 150); Insert into ACCOUNT_LOOCKUP (SERIAL_ID, ACCOUNT_ID, ACCOUNT_RATE, ACCOUNT_MAX) Values (3, 1, 8, 400); Insert into ACCOUNT_LOOCKUP (SERIAL_ID, ACCOUNT_ID, ACCOUNT_RATE, ACCOUNT_MAX) Values (1, 2, 7, 100); Insert into ACCOUNT_LOOCKUP (SERIAL_ID, ACCOUNT_ID, ACCOUNT_RATE, ACCOUNT_MAX) Values (2, 2, 5, 200); COMMIT; SELECT * FROM ACCOUNT_LOOCKUP SERIAL_ID ACCOUNT_ID ACCOUNT_RATE ACCOUNT_MAX ---------- ---------- ------------ ----------- 1 1 10 200 2 1 12 150 3 1 8 400 1 2 7 100 2 2 5 200 CREATE TABLE ACCOUNT_AMOUNT( ACCOUNT_ID NUMBER(10), ACCOUNT_AMNT NUMBER(10)) Insert into ACCOUNT_AMOUNT (ACCOUNT_ID, ACCOUNT_AMNT) Values (1, 9); Insert into ACCOUNT_AMOUNT (ACCOUNT_ID, ACCOUNT_AMNT) Values (1, 35); COMMIT; SELECT * FROM ACCOUNT_AMOUNT ACCOUNT_ID ACCOUNT_AMNT ---------- --------------- 1 9 1 35
I want by select query calculte ACCOUNT_TOTAL every ACCOUNT_ID exists in table ACCOUNT_AMOUNT as below , 1. every ACCOUNT_ID have SERIAL_ID and ACCOUNT_RATE and ACCOUNT_MAX in table ACCOUNT_LOOCKUP, 2. to calculte ACCOUNT_TOTAL every ACCOUNT_ID : - order ascending SERIAL_ID exists in table ACCOUNT_LOOCKUP to every ACCOUNT_ID exists in table ACCOUNT_AMOUNT , - make sum ACCOUNT_AMNT every ACCOUNT_ID in table ACCOUNT_AMOUNT, - then, copmare result (sum ACCOUNT_AMNT) with first record after ascending SERIAL_ID, - product (sum ACCOUNT_AMNT) * ACCOUNT_RATE result as ACCOUNT_TOTAL,(in ex: sum ACCOUNT_AMNT = 44 ) , - if ACCOUNT_TOTAL > ACCOUNT_MAX then * ACCOUNT_TOTAL = ACCOUNT_MAX for first record(in ex SERIAL_ID = 1 ) , * Goto the second record by ascending (in ex SERIAL_ID = 2 ) , make ( ACCOUNT_TOTAL / ACCOUNT_RATE ) for first record , ( 200 / 10 ) result 20 >> * calculate Remainder ACCOUNT_AMNT = the sum ACCOUNT_AMNT 44 - 20 = 24 *Goto the second record by ascending (in ex SERIAL_ID = 2 ) , Remainder ACCOUNT_AMNT 24 * (12) ACCOUNT_RATE for second record = 288 as ACCOUNT_TOTAL -if ACCOUNT_TOTAL > ACCOUNT_MAX then * ACCOUNT_TOTAL = ACCOUNT_MAX for second record(in ex SERIAL_ID = 2 ) , * Goto the third record by ascending (in ex SERIAL_ID = 3 ) , make ( ACCOUNT_TOTAL / ACCOUNT_RATE ) for second record , ( 150 / 12 ) result 12.5 * calculate Remainder ACCOUNT_AMNT = the sum ACCOUNT_AMNT 24 - 12.5 = 11.5 Remainder ACCOUNT_AMNT 9.5 * (12) ACCOUNT_RATE for third record = 92 result as ACCOUNT_TOTAL if result <= ACCOUNT_MAX then ACCOUNT_TOTAL = 92
except result ------------ SERIAL_ID ACCOUNT_ID ACCOUNT_RATE ACCOUNT_MAX ACCOUNT_TOTAL ** explain ** ---------- ---------- ------------ ----------- ------------- ***** sum ACCOUNT_AMNT = 44 for ACCOUNT_ID = 1from table ACCOUNT_AMOUNT ****** 1 1 10 200 200 >> (44 * 10 ) = 440 >> 200 /10 rate = 20 >> 44 - 20 = 24 Remainder ACCOUNT_AMNT 2 1 12 150 150 >> (22 * 12 ) = 288 >> 150 /12 rate = 12.5 >> 24 - 12.5 = 11.5 Remainder ACCOUNT_AMNT 3 1 8 400 92 >> (11.5 * 8) = 92 And so on ....
Help me pleaseanother insert Insert into ACCOUNT_AMOUNT (ACCOUNT_ID, ACCOUNT_AMNT) Values (2, 10); SELECT * FROM ACCOUNT_AMOUNT ACCOUNT_ID ACCOUNT_AMNT ---------- --------------- 1 9 1 35 2 10 except result ------------ SERIAL_ID ACCOUNT_ID ACCOUNT_RATE ACCOUNT_MAX ACCOUNT_TOTAL ** explain ** ---------- ---------- ------------ ----------- ------------- ***** sum ACCOUNT_AMNT = 10 for ACCOUNT_ID = 2 from table ACCOUNT_AMOUNT ****** 1 1 10 200 200 2 1 12 150 150 3 1 8 400 92 1 2 7 100 70 10 * 7 = 70
Thanks in advance
Published by: 900510 on December 5, 2011 08:05900510 wrote:
Hi allFirst I want to apologize for my English, this isn't flunet.
Following the script nicely:
CREATE OR REPLACE VIEW V_ACCOUNT (ACCOUNT_ID,ID,ACCOUNT_RATE,ACCOUNT_MAX,ACCOUNT_TOTAL) AS SELECT 1, 2, 10 ,200 , 0 FROM DUAL UNION SELECT 1, 5, 12 ,150 , 0 FROM DUAL UNION SELECT 1, 9, 8 ,400 , 0 FROM DUAL UNION SELECT 2 ,1, 7 ,100 , 0 FROM DUAL UNION SELECT 2 ,3 ,5 ,200 , 0 FROM DUAL ORDER BY 1,2 ACCOUNT_ID ID ACCOUNT_RATE ACCOUNT_MAX ACCOUNT_TOTAL ---------- ---------- ------------ ----------- ------------- 1 2 10 200 0 1 5 12 150 0 1 9 8 400 0 2 1 7 100 0 2 3 5 200 0
I must be missing something... in your opinion, by definition does only selected literals 5 double. How you expect what you do for any other table to change those returned by the view?
Published by: EdStevens on December 5, 2011 08:51
-
Hello everyone, I kindly need help with a query that I'm writing. I think it's supposed to be some kind of join, but I'm a little uncertain. Here is an example:
Select a.person_id, a.company, b.name, e.element, f.value
of a, b, e, f
where a.person_id = b.person_id
and e.el_id = f.el_id
-e.t.c
Lets say this returns
person_id, company, name, element value
------------------------------------------------------
1 vol., krog, breakfast, 34
2, mols, flog, munch, 24
The problem is now the table e. I want to get all the e table values that meet certain criteria. As in:
Select e.element
where e.name = "RATED."
Lets say this returns
element
-----------
food
lunch
Munch
And combine it with the query at the top of the page. But I also want to show all the other values, a.person_id, a.company, b.name for each line.
So my goal is to finally have:
person_id, company, name, element value
------------------------------------------------------
1 vol., krog, breakfast, 34
1 vol., krog, food, 0
1 vol., krog, munch, 0
2, mols, flog, munch, 24
2, mols, flog, food, 0
2, mols, flog, 0
It's to have a default value of zero, where no join does exist for the value and do not duplicate anything even if I could always use separate.
Can anyone help with this?with t1 as ( select a.person_id, a.company, b.name, e.element, f.value from a, b, e, f where a.person_id = b.person_id and e.el_id = f.el_id -- e.t.c ), t2 as ( select e.element where e.name = 'EVALUE' ) select person_id, company, name, t2.element, sum( case t1.element when t2.element then value else 0 end ) value from t1, t2 group by person_id, company, name, order by person_id, company, name, t2.element /
For example:
with t1 as ( select 1 person_id, 'Vols' company, 'krog' name, 'lunch' element, 34 value from dual union all select 2, 'Mols', 'flog', 'munch', 24 from dual ), t2 as ( select 'food' element from dual union all select 'lunch' from dual union all select 'munch' from dual ) select person_id, company, name, t2.element, sum( case t1.element when t2.element then value else 0 end ) value from t1, t2 group by person_id, company, name, t2.element order by person_id, company, name, t2.element / PERSON_ID COMP NAME ELEME VALUE ---------- ---- ---- ----- ---------- 1 Vols krog food 0 1 Vols krog lunch 34 1 Vols krog munch 0 2 Mols flog food 0 2 Mols flog lunch 0 2 Mols flog munch 24 6 rows selected. SQL>
SY.
Maybe you are looking for
-
How to recover lost saved the password in Gmail?
Hello, I got some Gmail accounts which, with the help of Firefox to remember passwords for them. But then, one day he showed no accounts or passwords saved when I tried to connect it. Now, I do not remember passwords and I panicked.
-
2570p: BIOS lost password - need the 2570p file SMC.bin
Hello I am located in the Japan and I need a SMC.bin file to reset the password of the bios for a 2570p here. I contacted the support to the Japan HP, but the only option that they provide is to send the machine and it will cost ~ $160 for repairs. I
-
Bluetooth/infrared M40-152
Hi people!My girlfriend bought justg one M40-152. How do you turn on the infrared device? (are there any)Same question for the bluetooth device. The Manager has always said that the device is not ready. Help, please!Thank you very muchAndreas
-
Hi all. Our Pavilion dv7 - 6143cl receives the following message when you start the laptop: The system has detected that a cooling fan does not work correctly.
-
EA4500 Router FTP Server Security
I have a general question around the FTP server on the EA4500, is it safe? I don't see any option to use TLS or SSL, or specify only implicit/explicit connections. Is it safe to use the FTP server to the external? Any help appreciated.