Group Query Help
Oracle 10G version | R/2This is a Customers table and we will have to find they are elgible for product produced B or both or none.
But if you're serviceble by product B, it is certain that you will be good product a. (imagine the product A is greater coverage of Prouct and be produced is the smallest)
What I have done becomes the product of A B and get the remains that are usable for the product and not product B.
< pre >
CREATE TABLE CUST_TEST
(
Number of cust_id,
Column_serviceable_A varchar2 (2),
Column_Serviceable_B varchar2 (2),
Column_Color_A varchar2 (2),
Column_Color_B varchar2 (2),
Area_OO varchar2 (2),
Area_H varchar2 (2),
Varchar2 (10) STATE
);
insert into cust_test (Cust_ID, Column_serviceable_A, Column_Serviceable_B, Column_Color_A, Column_Color_B, Area_OO, Area_H, STATE)
values(1,'Y','Y','G','G','Y','Y','HYD');
insert into cust_test (Cust_ID, Column_serviceable_A, Column_Serviceable_B, Column_Color_A, Column_Color_B, Area_OO, Area_H, STATE)
values(2,'Y','Y','G','G','Y','Y','HYD');
insert into cust_test (Cust_ID, Column_serviceable_A, Column_Serviceable_B, Column_Color_A, Column_Color_B, Area_OO, Area_H, STATE)
values(3,'Y',,'G',,'Y','Y','HYD');
insert into cust_test (Cust_ID, Column_serviceable_A, Column_Serviceable_B, Column_Color_A, Column_Color_B, Area_OO, Area_H, STATE)
values(4,'Y',,'R',,'Y','Y','BANG');
insert into cust_test (Cust_ID, Column_serviceable_A, Column_Serviceable_B, Column_Color_A, Column_Color_B, Area_OO, Area_H, STATE)
values(5,,,,,'Y','Y','BANG');
insert into cust_test (Cust_ID, Column_serviceable_A, Column_Serviceable_B, Column_Color_A, Column_Color_B, Area_OO, Area_H, STATE)
values(6,'Y','Y','G','G','Y','Y','CHEN');
insert into cust_test (Cust_ID, Column_serviceable_A, Column_Serviceable_B, Column_Color_A, Column_Color_B, Area_OO, Area_H, STATE)
values(7,'Y',,'G',,'Y','Y','CHEN');
insert into cust_test (Cust_ID, Column_serviceable_A, Column_Serviceable_B, Column_Color_A, Column_Color_B, Area_OO, Area_H, STATE)
values(8,'Y',,'G',,'Y','Y','CHEN');
< / pre >
< pre >
Select
(
(
Select sum (case when area_oo = 'Y' or area_h = 'Y' then 1 else 0 end) of CUST_TEST one
where column_serviceable_A = 'Y '.
and Column_Color_A ('g', 'A')
and status = 'HYD.
)
-
(
Select sum (case when area_oo = 'Y' or area_h = 'Y' then 1 else 0 end) of CUST_TEST one
where Column_Serviceable_B = 'Y '.
and Column_Color_B ('g', 'A')
and status = 'HYD.
)
)
Double;
< / pre >
But I need this 15 times as there are 15 States, I want to do in a single request via the Group of. CUST_TESTis also a view and each query takes once NGOs as customers there 15 million.
Please let me know if you need more information.
Desirable output;
COUNT (*) STATE
HYD 1
BANG null
CHEN 2
Thank you and best regards,
Cracky
Published by: CrackerJack 22 November 2010 16:51
Hello
Thanks for posting the sample data in a useful form. That really helps.
So you want a query that produces a line of output for each value in the column state.
That's exactly what "State GROUP BY" don't:
SELECT state
, COUNT ( CASE
WHEN column_serviceable_a = 'Y'
AND column_color_a IN ('G', 'A')
THEN 1
END
)
- COUNT ( CASE
WHEN column_serviceable_b = 'Y'
AND column_color_b IN ('G', 'A')
THEN 1
END
) AS cnt
FROM cust_test
WHERE area_oo = 'Y'
AND area_h = 'Y'
GROUP BY state
ORDER BY state
;
In fact, this becomes 0 as the county when no line meets the criteria of "has".
If you prefer that NULL, as you posted, then replace the first indictment by AMOUNT:
SELECT state
, SUM ( CASE
WHEN column_serviceable_a = 'Y'
AND column_color_a IN ('G', 'A')
THEN 1
END
)
- COUNT ( CASE
WHEN column_serviceable_b = 'Y'
AND column_color_b IN ('G', 'A')
THEN 1
END
) AS cnt
FROM cust_test
WHERE area_oo = 'Y'
AND area_h = 'Y'
GROUP BY state
ORDER BY state
;
Output:
STATE CNT
---------- ----------
BANG
CHEN 2
HYD 1
Note that we do not need duplicate in this problem. Whenever you are tempted to use double, ask yourself why. See if the information you want to be taken from another table that you use when even.
This should be much faster than the original request. Instead of making 2 passes through the table for each status value (2 * 15 = 30 past total), just make a pass through the table.
Published by: Frank Kulash, 22 November 2010 20:14
Simplified 2nd query (for number of NULL).
Tags: Database
Similar Questions
-
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
-
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...
-
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.
-
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;
-
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.
-
Hello
I'm new to the development of Oracle.
Oracle 10 g 2
My original query:
SELECT APP, count (*)
TRANSACTION
WHERE TYPE in ('ShipmentConfirmPR', 'ShipmentConfirm', 'ShipConfirm')
and the APP ("SAPPI", "SAPPI", "SAPR3") and INTERVENE ('9320 ', '9332','1208 ')
GROUP BY APP TYPE
order of the APP
the result of this query:
SAPPI 100
SAPPI 600
SAPR3 440
My requirement
And I want to have something like output
LDCS 100
TSW 600
PDC 440
IE.the APPP and STEP combinations. Must return the specified values
SAPPI & 9320-> LOC (here SAPPI IE APP is the same for both... but it's a coincidence IE APP can be sliced also)
SAPPI & 9332-> tsw
SAPR3 & 1208-> pdc
Options, I tried:
Query provided by one of the Forum members...
SELECT THE CHECK BOX
WHEN APP = "SAPP1" THEN DECODE (step, '9320', 'LSW', '9332', "TSW")
WHEN APP = "SAPR3" step = '1208' AND 'PDC '.
END app
COUNT (*)
TRANSACTION
WHERE TYPE in ('ShipmentConfirmPR', 'ShipmentConfirm', 'ShipConfirm')
AND THE APP ("SAPPI", "SAPPI", "SAPR3")
AND STEP IN ('9320', '9332', ' 1208')
GROUP BY APP, STEP
ORDER OF THE APP.
EXECUTION PLAN
| ID | Operation | Name |
------------------------------------------------------------------------
| 0 | SELECT STATEMENT |
| 1. GROUP SORT BY |
| 2. INLIST ITERATOR.
| 3. TABLE ACCESS BY INDEX ROWID | TRANSACTION |
| 4. INDEX RANGE SCAN | TRANSACTION_IDX |
The output of the query (as above) must partially match the following query (a particular combination of CLO)
SELECT count (1)
TIBCO. TRANSACTION_HISTORY
WHERE TYPE = 'ShipmentConfirm '.
and APP in ("SAPPI") and INTERVENE ('9332')
My Questions:
1.*There are indexes on all 3 APP passes it's IE, STEP and TYPE *. I don't want a FULL table Scan (as one would use the index). Can change us the query / use of indices, etc. to make it faster?
2. is the right to approach? Would the use of the concat operator in the function decode work better for my needs?
Something like
Select decode (APP |) STEP, 'SAPP9332', 'X') of TRANSACTION_HISTORY where < COND >
If Yes can you please provide the query?
3. ANY other approach / request for my requirement.
Thanks in advance.Hello
user13517642 wrote:
... EXECUTION PLAN| ID | Operation | Name |
------------------------------------------------------------------------
| 0 | SELECT STATEMENT |
| 1. GROUP SORT BY |
| 2. INLIST ITERATOR.
| 3. TABLE ACCESS BY INDEX ROWID | TRANSACTION |
| 4. INDEX RANGE SCAN | TRANSACTION_IDX |The output of the query (as above) must partially match the following query (a particular combination of CLO)
SELECT count (1)
TIBCO. TRANSACTION_HISTORY
WHERE TYPE = 'ShipmentConfirm '.
and APP in ("SAPPI") and INTERVENE ('9332')My Questions:
1.*There are indexes on all 3 APP passes it's IE, STEP and TYPE *. I don't want a FULL table Scan (as one would use the index). Can change us the query / use of indices, etc. to make it faster?
A full table scan might be the fastest way to get results. Do you have any reason to think that it would be faster to go through the index? How selective are the clues? In other words, what is the percentage of rows in the table correspond to each of the values in the WHERE clause?
2. is the right to approach?
It depends on what you're trying to do, which is not at all clear to me.
Would the use of the concat operator in the function decode work better for my needs?
Something likeSelect decode (APP |) STEP, 'SAPP9332', 'X') of TRANSACTION_HISTORY where
If you use this approach, look out for the problem Ab asse crevit . For example, if you have these 4 rows and 2 columns:
str1 str2 ---- ---- (NULL) FOO F OO FO O FOO (NULL)
There are 4 values of distict of str1 (counting NULL) and 4 separate values of str2, str1 but | str2 is the same for each of them. In the above example, it there is no way to know, just by looking at the concatenated string, including str1 and str2 ends begins. Maybe it's not the case for your specific data (for example, if the application is still exactly 5 characters long). otherwise, you may need to add some kind of delimiter, like this
app || '+' || step
where you know that '+' never occurs in one of these columns.
3. ANY other approach / request for my requirement.
CASES, as I mentioned in your previous message:
Decode the help function
and as you have used above.In this thread, you said "I have to use the decode function. Why? It is a competition of school Etudieeo DECODE is explicitly required? Why you don't want in the best way, what that turns out to be?
Your WHERE clause:
AND APP IN ('SAPPI', 'SAPPI', 'SAPR3') AND STEP IN ('9320', '9332', '1208')
admits 6 possible combinations of APA and step:
app step ----- ---- SAPP1 9320 SAPP1 9332 SAPP1 1208 SAPP3 9320 SAPP3 9332 SAPP3 1208
but you are looking for only 3 of these combinations in DECODE it or the expression BOX. (Have 2 copies of 'SAPP1' e list won't do any good, but it does hurt real, either.)
By the way, is "SAPPI" app with the letter 'I' at the end, or "SAPP1", with the number '1' at the end?Published by: Frank Kulash, March 24, 2011 19:44
-
SQl query help please...
Hello
I have a requirement... can help you pleease
I have a table with two columns called Doc R, Seq R
Sampled data:
Type Doc R Seq R -------- --------- ------------ R R1 Null Q Q1 R1 R R2 Null Q Q2 R2 R R3 Null Q Null Null Now if you see first two records R1 and R2 have corresponding Q2..... if you see R3 dont have Q values.. Now i want the count of R3 like records where it does not have Corresponding Q values in ... any ideas please...
Hello
Another way, which could be more efficient (but less clear):
WITH got_grp AS ( SELECT CASE WHEN rtype = 'Q' THEN seq_r ELSE doc_r END AS grp , CASE WHEN rtype = 'Q' THEN 0 ELSE 1 END AS r_val FROM yourtable WHERE rtype IN ('Q', 'R') ) SELECT COUNT (COUNT (*)) AS grp_cnt FROM got_grp GROUP BY grp HAVING COUNT (*) = SUM (r_val) ;
You have not said if a line where
rtype = 'R' and doc_r has the value NULL is considered to be a match for a line where
rtype = 'Q' and seq_r is NULL.In the application of Cyn, they are not a match.
In the above query, they are.
A query can be changed for a different result. -
The point list - record group Query - bad alignment order
Dear all,
When I try to concatenate two columns using the query of the record group and display in the list item, the alignment is not in good condition.
For example; Here are the columns and data used in the process:
SHORT_DESC CODE_VALUE DESCRIPTION
---------------------------------------------------------------------------------------------------------------------------------------------------
ROLL1 customer - No accidental Production, by booking with another carrier, bad projection.
Roll2 client project - accidental l/c, B/L, customs, samples, AMS, LAR.
ABC - lack of vacuum ROLL3 lack of empty units.
ABC CDE ROLL4 - Roll on decision of the AGR RRR.
ROLL5 ABC XXX - Accidental IMO or denied OOG, operational problems, Cut & Run.
ROLL6 ABC YYY - booking fictitious material buffer, dummy booking.
This is the query of the record group used in forms:
----------------------------------------------------------------
PROCEDURE p_when_new_form_instance
IS
GROUP_ID recordgroup;
list_id question: = FIND_ITEM ('BLK_CONTROL.) LI_ROLL_REASON');
rg_name VARCHAR2 (20): = "LI_ROLL_REASONS";
status NUMBER;
l_query VARCHAR2 (4000);
BEGIN
l_query: =.
' SELECT rpad (short_desc, 50, "") | "| ''|| description of the description, code_value code_value OF codes WHERE code_value IN ("ROLL1", "roll2", "ROLL3", "ROLL4", "ROLL5", "ROLL6")';
GROUP_ID: = CREATE_GROUP_FROM_QUERY (rg_name, l_query);
status: = POPULATE_GROUP (GROUP_ID);
POPULATE_LIST (list_id, GROUP_ID);
EXCEPTION
WHILE OTHERS
THEN
pl_common.when_others;
END;
-----------------------------------
In addition, I have my property list item as the default "" MS SANS SERIF"fonts and when I run in Forms Builder get the alignment as below.
Result:
====
DESCRIPTION CODE_VALUE
Customer - Non-accidental. Production, by booking with another carrier, bad projection. ROLL1
Customer - Accidental | L/c, B/L project, customs, samples, AMS, LAR. ROLL2
ABC - lack of vacuum | Lack of empty units. ROLL3
ABC ORDER - to the reversal. Decision of the AGR RRR. ROLL4
ABC XXX - Accidental | IMO / denied OOG, operational problems, Cut & Run. ROLL5
ABC YYY - booking fictitious | Reservation of equipment, fake buffer. ROLL6
More high of the order is not the desired result because all the | (vertical bar) should display in the correct order as below.
Expected result:
==========
DESCRIPTION CODE_VALUE
Customer - Non-accidental. Production, by booking with another carrier, bad projection. ROLL1
Customer - Accidental | L/c, B/L project, customs, samples, AMS, LAR. ROLL2
ABC - lack of vacuum | Lack of empty units. ROLL3
ABC ORDER - to the reversal. Decision of the AGR RRR. ROLL4
ABC XXX - Accidental | IMO / denied OOG, operational problems, Cut & Run. ROLL5
ABC YYY - booking fictitious | Reservation of equipment, fake buffer. ROLL6
I tried and RPAD LPAD the alignment problem is still there; I know that the issue is due to the fixed length of the police.
But is there a solution to replace it it will be a great help.
So please help!
Thank you...
Kind regards
Sunil.GIf you can not use non proportional fonts, then forget about having any special alignment, because with proportional fonts, room occupied by each letter is different.
François
-
Hello
Need help with writing a query.
Thanks in advanceSQL> SELECT xmlelement("P",xmlforest(P.process_id AS Ppid), 2 xmlagg(xmlelement("PI",XMLFOREST( PI.question_id AS PIqid, 3 PI.process_id AS PIpid, 4 PI.innertext AS PItext), 5 xmlagg(Xmlelement("PO",xmlforest( PO.option_id AS POoid, 6 PO.question_id AS POqid, 7 PO.process_id AS popid 8 )) 9 ORDER BY PO.option_id)) 10 ORDER BY PI.question_id ) ) 11 FROM liveProcess_ec P 12 INNER JOIN vw_liveProcessItem_Sim_v6 PI 13 ON P.process_id = PI.process_id 14 LEFT OUTER JOIN vw_liveProcessOption_Sim_v6 PO 15 ON PI.question_id = PO.question_id 16 AND PI.process_id = PO.process_id 17 WHERE p.process_id =450 18 GROUP BY p.process_id,PI.question_id,PI.process_id,PI.innertext 19 ORDER BY p.process_id; SELECT xmlelement("P",xmlforest(P.process_id AS Ppid), * ERROR at line 1: ORA-00937: not a single-group group function
I think you are looking for something like this:
SQL> SELECT 2 XMLAgg( 3 XMLElement("P" 4 ,XMLElement("Ppid",p.process_id) 5 ,XMLElement("qcount",100) 6 ,(SELECT 7 XMLAgg( 8 XMLELement("PI" 9 , XMLElement("PIqid", pi.question_id) 10 , XMLElement("PIpid", pi.process_id) 11 , XMLElement("PItext", pi.innertext) 12 , XMLAgg( 13 XMLElement("PO" 14 ,XMLForest( 15 po.option_id "POoid" 16 , po.question_id "POqid" 17 , po.process_id "POpid" 18 ) AS "PO" 19 ) 20 ) --xmlagg 21 ) --PI 22 ) --xmlagg 23 FROM 24 VW_LIVEPROCESSITEM_SIM_v6 pi 25 , VW_LIVEPROCESSOPTION_SIM_v6 po 26 WHERE p.process_id=pi.process_id 27 AND pi.question_id=po.question_id(+) 28 GROUP BY pi.question_id,pi.process_id,pi.innertext 29 )--select ended 30 ) 31 ) xm 32 FROM 33 liveprocess_ec p 34 GROUP BY p.process_id 35 ORDER BY p.process_id;
output
450 100 1 450 CBB1015 - Router Firewall Settinngs Process 2 450 Is the customers PC Firewall turned off? 1 2 450 2 2 450 3 450 Advise the customer to turn off the PC Firewall in order to continue. Has this been done? 1 3 450 2 3 450 16 450 Issue Resolved -
Dear Experts,
Need to convert several lines in a row
CREATE TABLE TESTING_PIVOT
(
IDENTIFICATION NUMBER,
NUMBER OF PRICE_AMOUNT
NUMBER OF RATE_PERCENT
);
INSERT INTO TESTING_PIVOT VALUES (1,100,55);
INSERT INTO TESTING_PIVOT VALUES (1,200,85);
INSERT INTO TESTING_PIVOT VALUES (1,300,64);
INSERT INTO TESTING_PIVOT VALUES (2,400,94);
INSERT INTO TESTING_PIVOT VALUES (2,500,59);
INSERT INTO TESTING_PIVOT VALUES (2,600,49);
COMMIT;
SELECT * FROM TESTING_PIVOT;
DESIREE OUTPUT
ID PRICE_AMOUNT_1 PRICE_AMOUNT_1 PRICE_AMOUNT_1 RATE_PERCENT_1 RATE_PERCENT_2 RATE_PERCENT_3
1 100 200 300 55 85 64
2 400 500 600 94 59 49
Help, please
Try this
Select
ID,
MAX (CASE WHEN RN = 1 THEN PRICE_AMOUNT END) PRICE_AMOUNT1,.
MAX (CASE WHEN RN = 2 THEN PRICE_AMOUNT END) PRICE_AMOUNT2,.
MAX (CASE WHEN RN = 3 THEN PRICE_AMOUNT END) PRICE_AMOUNT3,.
MAX (CASE WHEN RN = 1 THEN RATE_PERCENT END) RATE_PERCENT1,.
MAX (CASE WHEN RN = 2 THEN RATE_PERCENT END) RATE_PERCENT2,.
MAX (CASE WHEN RN = 3 THEN RATE_PERCENT END) RATE_PERCENT3
Of
(select id, PRICE_AMOUNT, RATE_PERCENT, ROW_NUMBER() over (PARTITION BY ORDER of the ROWNUM ID) RN OF TESTING_PIVOT)
Group by id;
-
SQL Query help find albums from sale
Hi Experts,
I have the following data and the need to find the book Top sold in each type.
Book Type QTY
20 Help the 3 10 Kitchen 1 5 Navigation 2 30 Help the 4 Please let me how can know we get this simple SQL help?
Thank you
Bharat
Hello
Bharat Hegde wrote:
Hi all
I tried to use Dense_rank as below. But it gives me the top selling books. I need high library in each type...
This looks like a job for 'PARTITION BY type
For example:
WITH got_rnk AS
(
SELECT b.bid, b.type
SUM (o.quantity) AS total_quantity
DENSE_RANK () OVER ( PARTITION BY b.type
ORDER OF SUM (o.quantity) / / DESC
) AS rnk
B BOOK
o order1
WHERE b.bid = o.bid
GROUP BY b.bid, b.type
)
SELECT total_quantity, type submission
OF got_rnk
WHERE rnk = 1
;
. Aggregate functions (such as the SUM, above) are calculated before analytical functions, so an analytic function (such as DENSE_RANK above) may depend on an aggregate function; you don't need a separate subquery for that.
-
Query help - to get the number of employees joined on each month regardless of the year
Hi all
I wrote the code below for number of employees joined each month regardless of the year of the employee table. But I couldn't get the result. Kindly help me where I'm wrong in my code,
Select to_char (hiredate, 'my') as join, count (empno) under the number
WCP
To_char Group (hiredate, 'my')
After having count (empno) > 1;
Your application displays the list of months (regardless of the year) where more than one employee was engaged with number of emplyees hired this month here. If you want months even if nobody was hired months thast, you emp table outer join to the list of every month:
with t as)
Select the level m
of the double
connect by level<=>=>
)
Select to_char (to_date (TM, 'mm'), 'my') Lun,
Count (e.empno) cnt
t
left join
E EMP
on Tahina = to_char (e.hiredate, 'mm')
Group of Tahina
order of Tahina
/
MY CNT
--- ----------
1 jan
February 2
Mar 0
Apr 2
May 2
1 Jun
July 0
August 0
2 sep
Oct 0
1 novMY CNT
--- ----------
Dec 312 selected lines.
SQL >
SY.
-
Hi all
I'm working on a query to the tables of dimensions. I want to be able to retrieve the total number of bytes and unused bytes for tables and their indexes. I also want to be able to combine all the output in several long strings to paste into simple rows of an Excel for analysis later. I could get that day:
DECLARE CURSOR size_cursor IS WITH obj_names AS ( SELECT s.owner, s.segment_name table_name, NULL, s.segment_type, s.partition_name, t.num_rows FROM dba_segments s, dba_tables t WHERE segment_type = 'TABLE' and t.table_name = s.segment_name and t.owner = s.owner UNION ALL SELECT s.owner, s.segment_name, NULL, s.segment_type, s.partition_name, t.num_rows FROM dba_segments s, dba_tables t WHERE segment_type = 'TABLE PARTITION' and t.table_name = s.segment_name and t.owner = s.owner UNION ALL SELECT i.owner, i.table_name, i.index_name, s.segment_type, partition_name, NULL FROM dba_indexes i, dba_segments s WHERE s.segment_name = i.index_name AND s.owner = i.owner AND s.segment_type = 'INDEX' ) SELECT * FROM obj_names; tbl_owner varchar2(32767); tbl_name varchar2(32767); index_name varchar2(32767); tbl_type varchar2(32767); row_count number; total_blocks_out number; total_bytes_out number; unused_blocks_out number; unused_bytes_out number; last_used_extent_file_id_out number; last_used_extent_block_id_out number; last_used_block_out number; BEGIN OPEN size_cursor; LOOP FETCH size_cursor INTO tbl_owner, tbl_name, index_name, tbl_type, part_name, row_count; EXIT WHEN size_cursor%NOTFOUND; dbms_space.unused_space( tbl_owner, COALESCE(index_name, tbl_nadme), tbl_type, total_blocks_out, total_bytes_out, unused_blocks_out, unused_bytes_out, last_used_extent_file_id_out, last_used_extent_block_id_out, last_used_block_out, part_name ); END LOOP; CLOSE size_cursor;ND;
Yet, cannot figure out how to group then tbl_owner and tble_name without inserting the results of cursor in a table, that I can't do. Any suggestions on how to perform the dbms_space.unused_space procedure to store without using a cursor? I have SQL Server I would be cheating by using sp_MSforeachtable, that would allow me to keep the results of the stored procedure as a relationship.
Thanks for any ideas or suggestions.
So I thought about my own questions by using the following query instead of the stored procedure...
select dba_tables.owner ,dba_tables.table_name ,dba_tables.num_rows "rows" ,sz + ex "Total reserved (KB)" ,dba_tables.num_rows*dba_tables.avg_row_len/1024 "data size (KB)" , sz "index reserved size (KB)" from (select table_name as table_name, sum(bytes)/1024 as sz ,max(pct_free) as free from dba_indexes inner join dba_extents on index_name=segment_name group by table_name) ix_space inner join dba_tables on ix_space.table_name=dba_tables.table_name inner join (select segment_name,sum(bytes)/1024 ex from dba_extents group by segment_name) ext on ext.segment_name=dba_tables.table_name
Maybe you are looking for
-
How to write the Date/time of the PDM file property
On the page root of the PDM file, there is a predefined, property called ' Date/Time' in the first row. I would use it to save the timestamp when the tdms file is created. But in the help file. I find that the following property constant. So, how can
-
Can my computer games MS-DOS?
I have a Windows XP service pack 3 Compaq Presario SR1124NX, so I was wondering if I would be able to play MS-DOS games. So my computer could run them? Thank you!!!
-
Why change my screen resolution?
While in the sleep or still more now using PCs, the revert at 800 x 600 resolution when the correct wreck is 1440 x 900, it is the only res that seems correct and what its always been on
-
I have a big problem with Windows Live essentials 2011. 0x8007064c error code
I have a big problem with Windows Live essentials 2011. I can't find in Add and remove programs or in C:\program files to remove it if I can reinstall it. I went through the registry and deleted all instances of it. When I try to reinstall, I get
-
packaging by ripple works ok, but no launch
Hello Everything started playing with WebWorks today (OS of PB). Tried to start my own first HelloWorld app. Packaging by ripple works very well, I see the .bar file. But trying to launch my (physical) PlayBook, the package & launch batch stops. No e