Join "Decode" and a "Simple Query"
Hi everyone, i have two queries which i have failed to join.
The first query is:
select "STUDENTDETAILS"."TITLE" as "TITLE",
"STUDENTDETAILS"."FIRSTNAME" as "FIRSTNAME",
"STUDENTDETAILS"."MIDDLENAME" as "MIDDLENAME",
"STUDENTDETAILS"."LASTNAME" as "LASTNAME",
"STUDENTDETAILS"."DATEOFBIRTH" as "DATEOFBIRTH",
"STUDENTDETAILS"."AGE" as "AGE",
"STUDENTDETAILS"."GENDER" as "GENDER",
"STUDENTDETAILS"."MARRITAL_STATUS" as "MARRITAL_STATUS",
"STUDENTDETAILS"."NRC_NUMBER" as "NRC_NUMBER",
"STUDENTDETAILS"."REGISTERED_BY" as "REGISTERED_BY",
"STUDENTDETAILS"."APPLICATIONNUMBER" as "APPLICATIONNUMBER",
"ADDRESS"."PHONE_NUMBER1" as "PHONE_NUMBER1",
"ADDRESS"."PHONE_NUMBER2" as "PHONE_NUMBER2",
"ADDRESS"."E-MAIL_ADDRESS" as "E-MAIL_ADDRESS",
"ADDRESS"."ADDRESS1" as "ADDRESS1",
"ADDRESS"."ADDRESS2" as "ADDRESS2",
"ADDRESS"."COMPOUND" as "COMPOUND",
"ADDRESS"."POSTAL_BOX" as "POSTAL_BOX",
"ADDRESS"."DISTRICT" as "DISTRICT",
"ADDRESS"."PROVINCE" as "PROVINCE"
from "ADDRESS" "ADDRESS",
"STUDENTDETAILS" "STUDENTDETAILS"
where "ADDRESS"."APPLICATIONNUMBER"="STUDENTDETAILS"."APPLICATIONNUMBER"
Second query is:
select studentdetails.
applicationnumber
,min(DECODE(SUBJECT,'MATHEMATICS', SUBJECT_SCORE)) as "MATHEMATICS"
,min(DECODE(SUBJECT,'ENGLISH', SUBJECT_SCORE)) as "ENGLISH"
,min(DECODE(SUBJECT,'BIOLOGY', SUBJECT_SCORE)) as "BIOLOGY"
,min(DECODE(SUBJECT,'SCIENCE', SUBJECT_SCORE)) as "SCIENCE"
,min(DECODE(SUBJECT,'COMMERCE', SUBJECT_SCORE)) as "COMMERCE"
,min(DECODE(SUBJECT,'ZAMBIAN LANGUAGE', SUBJECT_SCORE)) as "ZAMBIAN LANGUAGE"
,min(DECODE(SUBJECT,'ART', SUBJECT_SCORE)) as "ART"
from "SUBJECTS" "SUBJECTS",
"STUDENT_SCORES" "STUDENT_SCORES",
"STUDENTDETAILS" "STUDENTDETAILS"
where "STUDENTDETAILS"."APPLICATIONNUMBER"="STUDENT_SCORES"."APPLICATIONNUMBER"
and "STUDENT_SCORES"."SUBJECT_ID"="SUBJECTS"."SUBJECT_ID"
group by studentdetails.applicationnumber
order by studentdetails.applicationnumber
i need to join the two to have this:
APPLICATIONNUMBER
TITLE
FIRSTNAME
MIDDLENAME
LASTNAME
DATEOFBIRTH
AGE
GENDER
MARRITAL_STATUS
NRC_NUMBER
REGISTERED_BY
MATHEMATICS
ENGLISH
BIOLOGY
SCIENCE
COMMERCE
ZAMBIAN LANGUAGE
ART
201300001
Mr
Lawrence
Mukombo
12/11/1980
33
Male
Married
219879/24/1
SYSTEM
2
1
4
3
4
5
1
Thanks in advance
Hi,
We do not know anything about your data model.
It is impossible help without sample data.
Also, this is Application Express forum and your question do not relate anyhow this product.
You should post these kind questions in SQL and PL/SQL forum.
Regards,
Jari
Similar Messages
-
The following query throws up 'Not a group by Expression' Error:
select decode(visited_last_date,sysdate,'Present','null') ,forum_name
from disc_forum f, disc_emp_pref p
where f.forum_category='TSP'
and f.forum_short_name=p.forum_short_name group by f.forum_short_name
How can i get this working? I need to retain the group-by clause.Thanx Detlev,
The query works with the group fn. But the actual query that i'm working on is:
select DECODE(visited_last_date,sysdate,'<img src="/images/on.gif">','null') img, ''| |f.forum_name| |'' forum_name, count(message_id) Posts, to_char(max(m.posted_date),'DD-MON-YYYY') last_updated from disc_message m, disc_thread t,disc_forum f,disc_emp_pref p where f.forum_category=nvl(:category,f.forum_category) and f.forum_short_name=t.forum_short_name(+) and t.thread_id=m.thread_id(+) group by cube(f.forum_name,f.forum_short_name,f.forum_description,p.visited_last_date)
I'm using this query to build a report in Oracle Portal. This query is working only that i'm getting duplicate rows. If i don't include the visited_last_date in the group_by clause then it flags a 'Not a group-by expr' error. How do i avoid that -
Simple Query working on 10G and not working on 11gR2 after upgrade
Hi Folks,
This is the first time i am posting the query in this Blog.
I have a small issue which preventing the UAT Sigoff.
Simple query working fine on 10.2.0.1 and after upgrade to 11.2.0.1 its error out
10.2.0.4:
=====
SQL> SELECT COUNT(*) FROM APPS.HZ_PARTIES HP WHERE ATTRIBUTE_CATEGORY= 'PROPERTY' AND ATTRIBUTE1=1;
COUNT(*)
1
SQL> SELECT COUNT(*) FROM APPS.HZ_PARTIES HP WHERE ATTRIBUTE_CATEGORY= 'PROPERTY' AND ATTRIBUTE1=00001;
COUNT(*)
1
SQL> select ATTRIBUTE1 FROM APPS.HZ_PARTIES HP WHERE ATTRIBUTE_CATEGORY= 'PROPERTY' AND ATTRIBUTE1=1;
ATTRIBUTE1
00001
11.2.0.1:
=====
SQL> SELECT COUNT(*) FROM APPS.HZ_PARTIES HP WHERE ATTRIBUTE_CATEGORY= 'PROPERTY' AND ATTRIBUTE1=1
ERROR at line 1:
ORA-01722: invalid number
SQL> SELECT COUNT(*) FROM APPS.HZ_PARTIES HP WHERE ATTRIBUTE_CATEGORY= 'PROPERTY' AND ATTRIBUTE1=00001
ERROR at line 1:
ORA-01722: invalid number
SQL> select ATTRIBUTE1 FROM APPS.HZ_PARTIES HP WHERE ATTRIBUTE_CATEGORY= 'PROPERTY' AND ATTRIBUTE1='1';
no rows selected
SQL> SELECT COUNT(*) FROM APPS.HZ_PARTIES HP WHERE ATTRIBUTE_CATEGORY= 'PROPERTY' AND ATTRIBUTE1='00001';
COUNT(*)
1
SQL> select ATTRIBUTE1 FROM APPS.HZ_PARTIES HP WHERE ATTRIBUTE_CATEGORY= 'PROPERTY' AND ATTRIBUTE1='00001';
ATTRIBUTE1
00001
++++++++++++++++++++++++++++++++++++++++++++++
SQL > desc APPS.HZ_PARTIES
Name Type
======== ======
ATTRIBUTE1 VARCHAR2(150)
++++++++++++++++++++++++++++++++++++++++++++++
Changes:
Recently i upgraded the DB from 10.2.0.4 to 11.2.0.1
Query:
1.If the type of that row is VARCHAR,why it is working in 10.2.0.4 and why not working in 11.2.0.1
2.after upgrade i analyzed the table with "analyze table " query for all AP,AR,GL,HR,BEN,APPS Schemas--Is it got impact if we run analyze table.
Please provide me the answer for above two questions or refer the document is also well enough to understand.Based on the Answer client will sigoff to-day.
Thanks,
P KumarWhiteHat wrote:
the issue has already been identified: in oracle versions prior to 11, there was an implicit conversion of numbers to characters. your database has a character field which you are attempting to compare to a number.
i.e. the string '000001' is not in any way equivalent to the number 1. but Oracle 10 converts '000001' to a number because you are asking it to compare to the number you have provided.
version 11 doesn't do this anymore (and rightly so).
the issue is with the bad code design. you can either: use characters in the predicate (where field = 'parameter') or you can do a conversion of the field prior to comparing (where to_num(field) = parameter).
I would suggest that you should fix your code and don't assume that '000001' = 1I don't think that the above is completely correct, and a simple demonstration will show why. First, a simple table on Oracle Database 10.2.0.4:
CREATE TABLE T1(C1 VARCHAR2(20));
INSERT INTO T1 VALUES ('1');
INSERT INTO T1 VALUES ('0001');
COMMIT;A select from the above table, relying on implicit data type conversion:
SELECT
FROM
T1
WHERE
C1=1;
C1
1
0001Technically, the second row should not have been returned as an exact match. Why was it returned, let's take a look at the actual execution plan:
SELECT
FROM
TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL,NULL,NULL));
SQL_ID g6gvbpsgj1dvf, child number 0
SELECT * FROM T1 WHERE C1=1
Plan hash value: 3617692013
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 2 (100)| |
|* 1 | TABLE ACCESS FULL| T1 | 2 | 24 | 2 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - filter(TO_NUMBER("C1")=1)
Note
- dynamic sampling used for this statementNotice that the VARCHAR2 column was converted to a NUMBER, so if there was any data in that column that could not be converted to a number (or NULL), we should receive an error (unless the bad rows are already removed due to another predicate in the WHERE clause). For example:
INSERT INTO T1 VALUES ('.0001.');
SELECT
FROM
T1
WHERE
C1=1;
SQL> SELECT
2 *
3 FROM
4 T1
5 WHERE
6 C1=1;
ERROR:
ORA-01722: invalid numberNow the same test on Oracle Database 11.1.0.7:
CREATE TABLE T1(C1 VARCHAR2(20));
INSERT INTO T1 VALUES ('1');
INSERT INTO T1 VALUES ('0001');
COMMIT;
SELECT
FROM
T1
WHERE
C1=1;
C1
1
0001
SELECT
FROM
TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL,NULL,NULL));
SQL_ID g6gvbpsgj1dvf, child number 0
SELECT * FROM T1 WHERE C1=1
Plan hash value: 3617692013
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | | | 2 (100)| |
|* 1 | TABLE ACCESS FULL| T1 | 2 | 24 | 2 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - filter(TO_NUMBER("C1")=1)
Note
- dynamic sampling used for this statement
INSERT INTO T1 VALUES ('.0001.');
SELECT
FROM
T1
WHERE
C1=1;
SQL> SELECT
2 *
3 FROM
4 T1
5 WHERE
6 C1=1;
ERROR:
ORA-01722: invalid numberAs you can see, exactly the same actual execution plan, and the same end result.
The OP needs to determine if non-numeric data now exists in the column. Was the database characterset possibly changed during/after the upgrade?
Charles Hooper
Co-author of "Expert Oracle Practices: Oracle Database Administration from the Oak Table"
http://hoopercharles.wordpress.com/
IT Manager/Oracle DBA
K&M Machine-Fabricating, Inc. -
Simple query takes time to run
Hi,
I have a simple query whcih takes about 20 mins to run.. here is the TKPROF forit:
SELECT
SY2.QBAC0,
sum(decode(SALES_ORDER.SDCRCD,'USD', SALES_ORDER.SDAEXP,'CAD', SALES_ORDER.SDAEXP /1.0452))
FROM
JDE.F5542SY2 SY2,
JDE.F42119 SALES_ORDER,
JDE.F0116 SHIP_TO,
JDE.F5542SY1 SY1,
JDE.F4101 PRODUCT_INFO
WHERE
( SHIP_TO.ALAN8=SALES_ORDER.SDSHAN )
AND ( SY1.QANRAC=SY2.QBNRAC and SY1.QAOTCD=SY2.QBOTCD )
AND ( PRODUCT_INFO.IMITM=SALES_ORDER.SDITM )
AND ( SY2.QBSHAN=SALES_ORDER.SDSHAN )
AND ( SALES_ORDER.SDLNTY NOT IN ('H ','HC','I ') )
AND ( PRODUCT_INFO.IMSRP1 Not In (' ','000','689') )
AND ( SALES_ORDER.SDDCTO IN ('CO','CR','SA','SF','SG','SP','SM','SO','SL','SR') )
AND (
( SY1.QACTR=SHIP_TO.ALCTR )
AND ( PRODUCT_INFO.IMSRP1=SY1.QASRP1 )
GROUP BY
SY2.QBAC0
call count cpu elapsed disk query current rows
Parse 1 0.07 0.07 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 10 92.40 929.16 798689 838484 0 131
total 12 92.48 929.24 798689 838484 0 131
Misses in library cache during parse: 1
Optimizer goal: CHOOSE
Parsing user id: 62
Rows Row Source Operation
131 SORT GROUP BY
3535506 HASH JOIN
4026100 HASH JOIN
922 TABLE ACCESS FULL OBJ#(187309)
3454198 HASH JOIN
80065 INDEX FAST FULL SCAN OBJ#(30492) (object id 30492)
3489670 HASH JOIN
65192 INDEX FAST FULL SCAN OBJ#(30457) (object id 30457)
3489936 PARTITION RANGE ALL PARTITION: 1 9
3489936 TABLE ACCESS FULL OBJ#(30530) PARTITION: 1 9
97152 TABLE ACCESS FULL OBJ#(187308)
OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 1 0.07 0.07 0 0 0 0
Execute 2 0.00 0.00 0 0 0 0
Fetch 10 92.40 929.16 798689 838484 0 131
total 13 92.48 929.24 798689 838484 0 131
Misses in library cache during parse: 1kindly suggest how to resolve this...
OS is windows and its 9i DB...
Thanks> ... you want to get rid of the IN statements.
They prevent Oracle from usering the index.
SQL> create table mytable (id,num,description)
2 as
3 select level
4 , case level
5 when 0 then 0
6 when 1 then 1
7 else 2
8 end
9 , 'description ' || to_char(level)
10 from dual
11 connect by level <= 10000
12 /
Table created.
SQL> create index i1 on mytable(num)
2 /
Index created.
SQL> exec dbms_stats.gather_table_stats(user,'mytable')
PL/SQL procedure successfully completed.
SQL> set autotrace on explain
SQL> select id
2 , num
3 , description
4 from mytable
5 where num in (0,1)
6 /
ID NUM DESCRIPTION
1 1 description 1
1 row selected.
Execution Plan
Plan hash value: 2172953059
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 5001 | 112K| 2 (0)| 00:00:01 |
| 1 | INLIST ITERATOR | | | | | |
| 2 | TABLE ACCESS BY INDEX ROWID| MYTABLE | 5001 | 112K| 2 (0)| 00:00:01 |
|* 3 | INDEX RANGE SCAN | I1 | 5001 | | 1 (0)| 00:00:01 |
Predicate Information (identified by operation id):
3 - access("NUM"=0 OR "NUM"=1)Regards,
Rob. -
Trying to optimize this simple query
Hi,
I am trying to optimize this simple query but the two methods I am trying actually make things worse.
The original query is:
SELECT customer_number, customer_name
FROM bsc_pdt_account_mv
where rownum <= 100
AND Upper(customer_name) like '%SP%'
AND customer_id IN
SELECT cust_id FROM bsc_pdt_assoc_sales_force_mv
WHERE area_identifier IN (
SELECT area_identifier FROM bsc_pdt_assoc_sales_force_mv
WHERE ad_identifier = '90004918' or rm_identifier = '90004918' or tm_identifier = '90004918'
The result set of this query returns me the first 100 rows in 88 seconds and they are all distinct by default (don't know why they are distinct).
My first attempt was to try to use table joins instead of the IN conditions:
SELECT
distinct -- A: I need to use distinct now
customer_number, customer_name
FROM bsc_pdt_account_mv pdt,
bsc_pdt_assoc_sales_force_mv asf,
SELECT distinct area_identifier FROM bsc_pdt_assoc_sales_force_mv
WHERE ad_identifier = '90004918' or rm_identifier = '90004918' or tm_identifier = '90004918'
) area
where
area.area_identifier = asf.area_identifier
AND asf.cust_id = pdt.customer_id
AND Upper(customer_name) like '%SP%'
AND rownum <= 100 -- B: strange when I comment this out
order by 1
I dont understand two things with this query. First issue, I now need to put in the distinct because the result set is not distinct by default. Second issue (very strange), when I put the rownum condition (<100) I get two rows in 1.5 seconds. If I remove the condition, I get 354 rows (whole result set) in 326 seconds.
My second attempt was to use EXISTS instead of IN:
SELECT
customer_number, customer_name
FROM bsc_pdt_account_mv pdt
where Upper(customer_name) like '%SP%'
AND rownum <= 100
AND EXISTS
select 1 from
bsc_pdt_assoc_sales_force_mv asf,
SELECT distinct area_identifier FROM bsc_pdt_assoc_sales_force_mv
WHERE ad_identifier = '90004918' or rm_identifier = '90004918' or tm_identifier = '90004918'
) area
where
area.area_identifier = asf.area_identifier
AND asf.cust_id = pdt.customer_id
This query returns a similar distinct result set as teh original one but takes pretty much the same time (87 seconds).The query below hangs when run in TOAD or PL/SQL Dev. I noticed there is no rows returned from the inner table for this condition.
SELECT customer_number, customer_name
FROM
bsc_pdt_account_mv pdt_account
where rownum <= 100
AND exists (
SELECT pdt_sales_force.cust_id
FROM bsc_pdt_assoc_sales_force_mv pdt_sales_force
WHERE pdt_account.customer_id = pdt_sales_force.cust_id
AND (pdt_sales_force.rm_identifier = '90007761' or pdt_sales_force.tm_identifier = '90007761') )
ORDER BY customer_name
-- No rows returned by this query
SELECT pdt_sales_force.cust_id
FROM bsc_pdt_assoc_sales_force_mv pdt_sales_force
WHERE pdt_sales_force.rm_identifier = '90007761' or pdt_sales_force.tm_identifier = '90007761' -
Following is a simple query, what i want to know, i have added upper select to get d.name which is the description of region_code. Can i get whole result with single select
SELECT t.region_code,d.name, t.emp_contr
FROM
(SELECT c.br_region_fo_code as Region_Code,
SUM(c.employer_contribution) AS emp_contr
FROM core_business.cb_contr_emp_pmt_slip c
GROUP BY c.br_region_fo_code ) t,
general_information.cb_region_fo d
WHERE t.br_region_fo_code = d.region_fo_code;Boneist wrote:
malhi wrote:
Following is a simple query, what i want to know, i have added upper select to get d.name which is the description of region_code. Can i get whole result with single select
SELECT t.region_code,d.name, t.emp_contr
FROM
(SELECT c.br_region_fo_code as Region_Code,
SUM(c.employer_contribution) AS emp_contr
FROM core_business.cb_contr_emp_pmt_slip c
GROUP BY c.br_region_fo_code ) t,
general_information.cb_region_fo d
WHERE t.br_region_fo_code = d.region_fo_code;To be honest, I wouldn't bother rewriting the above query - it looks like it's filtering early (although Oracle could choose to rewrite it so that it does the join first, I guess), so that you're reducing the number of rows that the outer query has to join to. That means less work. If it is rewriting, I'd stick a no_merge hint on the subquery, to tell Oracle to do the grouping first before joining.
You could rewrite the above query as:
SELECT c.br_region_fo_code AS region_code,
d.name,
SUM(c.employer_contribution) AS emp_contr
FROM core_business.cb_contr_emp_pmt_slip c,
general_information.cb_region_fo d
WHERE t.br_region_fo_code = d.region_fo_code
GROUP BY c.br_region_fo_code, d.name;but whether Oracle will filter early or not is another matter. You would have to test both runs.I believe that Jonathan Lewis had a demonstration of execution plans that showed Oracle transforming queries to "push" GROUP BY clause prior to a join when sufficient contraints were in place to allow that and there was a performance benefit in doing so. I'd certainly be interested in seeing whether this was being done. The optimisation was really aimed at reducing the size of the group by key columns. -
Hi,
I'm using Oracle 10g r2.
I have this simple query that seems to take too much time to execute :
DECLARE
nb_mesures INTEGER;
min_day DATE;
max_day DATE;
BEGIN
SELECT
COUNT(meas_id),
MIN(meas_day),
MAX(meas_day)
INTO
nb_mesures,
min_day,
max_day
FROM
geodetic_measurements gm
INNER JOIN
operation_measurements om
ON gm.meas_id = om.ogm_meas_id
WHERE ogm_op_id = 0;
htp.p(nb_mesures||' measurements from '||min_day||' to '||max_day);
END;- Tables (about 11.000 records for the "Operations" table, and 800.000 for the 2 others) :
"Operation_measurements" is the table who makes the link between the 2 others (get the 2 keys).
SQL> DESCRIBE OPERATIONS
Nom NULL Type
OP_ID NOT NULL NUMBER(7)
OP_PARENT_OP_ID NUMBER(7)
OP_RESPONSIBLE NOT NULL VARCHAR2(10)
OP_DESCRIPT VARCHAR2(80)
OP_VEDA_NAME NOT NULL VARCHAR2(10)
OP_BEGIN NOT NULL DATE
OP_END DATE
OP_INSERT_DATE DATE
OP_LAST_UPDATE DATE
OP_INSERT_BY VARCHAR2(50)
OP_UPDATE_BY VARCHAR2(50)
SQL> DESCRIBE OPERATION_MEASUREMENTS
Nom NULL Type
OGM_MEAS_ID NOT NULL NUMBER(7)
OGM_OP_ID NOT NULL NUMBER(6)
OGM_INSERT_DATE DATE
OGM_LAST_UPDATE DATE
OGM_INSERT_BY VARCHAR2(50)
OGM_UPDATE_BY VARCHAR2(50)
SQL> DESCRIBE GEODETIC_MEASUREMENTS
Nom NULL Type
MEAS_ID NOT NULL NUMBER(7)
MEAS_TYPE NOT NULL VARCHAR2(2)
MEAS_TEAM NOT NULL VARCHAR2(10)
MEAS_DAY NOT NULL DATE
MEAS_OBJ_ID NOT NULL NUMBER(6)
MEAS_STATUS VARCHAR2(1)
MEAS_COMMENT VARCHAR2(150)
MEAS_DIRECTION VARCHAR2(1)
MEAS_DIST_MODE VARCHAR2(2)
MEAS_SPAT_ID NOT NULL NUMBER(7)
MEAS_INST_ID NUMBER(7)
MEAS_DECALAGE NUMBER(8,5)
MEAS_INST_HEIGHT NUMBER(8,5)
MEAS_READING NOT NULL NUMBER(11,5)
MEAS_CORRECT_READING NUMBER(11,5)
MEAS_HUMID_TEMP NUMBER(4,1)
MEAS_DRY_TEMP NUMBER(4,1)
MEAS_PRESSURE NUMBER(4)
MEAS_HUMIDITY NUMBER(2)
MEAS_CONSTANT NUMBER(8,5)
MEAS_ROLE VARCHAR2(1)
MEAS_INSERT_DATE DATE
MEAS_LAST_UPDATE DATE
MEAS_INSERT_BY VARCHAR2(50)
MEAS_UPDATE_BY VARCHAR2(50)
MEAS_TILT_MODE VARCHAR2(4000) - Explain plan (I'm not familiar with explain plans...) :
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
PLAN_TABLE_OUTPUT
| 0 | SELECT STATEMENT | | 1 | 19 | 256 (10)| 00:00:02 |
| 1 | SORT AGGREGATE | | 1 | 19 | | |
| 2 | NESTED LOOPS | | 75 | 1425 | 256 (10)| 00:00:02 |
|* 3 | TABLE ACCESS FULL | OPERATION_MEASUREMENTS | 75 | 600 | 90 (27)| 00:00:01 |
| 4 | TABLE ACCESS BY INDEX ROWID| GEODETIC_MEASUREMENTS | 1 | 11 | 3 (0)| 00:00:01 |
|* 5 | INDEX UNIQUE SCAN | MEAS_PK_2 | 1 | | 2 (50)| 00:00:01 |
--------------------------------------------------------------------------------------------------------How can I optimize this query ?
Thanks.
Yann.Looks like you are missing an FK-index on the middle table, for the FK going to OPERATIONS.
Currently this:
WHERE ogm_op_id = 0;Is computed via a full table scan followed by a filter operation. Assuming OP_ID is rather selective, an index on OGM_OP_ID could do the trick here. -
Hi ,
I'm running the following simple query in sql*plus on ORACLE9i. But this query stopped running after 30minutes, and the sql*plus die at the same time .I have no idea about this. Could somebody tell me how I can solve this problem. Thank you very much for your help.
Select Distinct PERSADDRUSE. ADDRUSECD as "Application", PERS.PERSNBR as "Account",
(PERS.FIRSTNAME || ' '|| PERS.MDLINIT ||' ' || PERS.LASTNAME ) as "Name1",' 'as "Name2",' 'as "Name3",
AL1.TEXT as "Address1",AL2.TEXT as "Address2",AL3.TEXT as "Address3",
(ADDR.CITYNAME ||' ' || ' '||ADDR.STATECD ||' '||ADDR.ZIPCD||' '|| ADDR.ZIPSUF) as "CityStateZip"
From PERSADDRUSE
Join PERS
ON PERS.PERSNBR = PERSADDRUSE.PERSNBR
--AND PERS.ADDDATE = '12-JAN-2005'
AND PERSADDRUSE.ADDRUSECD = 'PRI'
join ADDR
ON PERSADDRUSE.ADDRNBR = ADDR.ADDRNBR
left JOIN ADDRLINE AL1
ON ADDR.ADDRNBR = AL1.ADDRNBR
AND AL1.LINENBR = 1
left JOIN ADDRLINE AL2
ON ADDR.ADDRNBR = AL2.ADDRNBR
AND AL2.LINENBR = 2
left JOIN ADDRLINE AL3
ON ADDR.ADDRNBR = AL3.ADDRNBR
AND AL3.LINENBR = 3;Thanks for reply. I have some other query running for 45m and it seems fine. The following are the explain plan I print out. I'm new to PL/SQL.Could you guys give me some other ideas?
BMS_XPLAN.DISPLAY()(PLAN_TABLE_OUTPUT)
PERSADDRUSE | 5726 | 68712 | 183 |'), DBMS_XPLAN_TYPE('| 8 | TABLE ACCESS FULL| PERS | 161K| 2839K| 431 |'), DBMS_XPLAN_TYPE('| 9 | TABLE ACCESS FULL | ADDR | 239K| 5145K| 298 |'), DBMS_XPLAN_TYPE('| 10 | TABLE ACCESS FULL | ADDRLINE | 82087 | 1683K| 240 |'), DBMS_XPLAN_TYPE('| 11 | TABLE ACCESS FULL | ADDRLINE | 82087 | 1683K| 240 |'), DBMS_XPLAN_TYPE('| 12 | TABLE ACCESS FULL | ADDRLINE | 82087 | 1683K| 240 |'), DBMS_XPLAN_TYPE('------------------------------------------------------------------------'), DBMS_XPLAN_TYPE(' '), DBMS_XPLAN_TYPE('Note: cpu costing is off, PLAN_TABLE'' is old version')) -
Select list and subquery: "LOV query is invalid"
Hi all,
I want to create a select list with the following format:
"name1 (count of another table)"
"name2 (count of another table)"
I've boiled it down to a simple query with a non-correlated subquery that works fine in SQL*Plus but not as an LOV:
select table1.field1 || (select count(*) from table2) d,
table1.field2 r
from table1
I get this (Apex 3.2.1):
1 error has occurred
* LOV query is invalid, a display and a return value are needed, the column names need to be different. If your query contains an in-line query, the first FROM clause in the SQL statement must not belong to the in-line query.
Even this doesn't work:
select table1.field1 || (select 'a' from dual) d,
table1.field2 r
from table1
I've tried it with an inline view, joining table1 to a select from table2 that returns the count, but I get the same result. Any ideas?
Edited by: MalcA on Jan 22, 2010 12:14 PMI don't know, but the difference is that the count(*) code goes from the select clause to the from clause.
Other times I had the same problem and always did it and it was the solution. -
consider this situation,
Two or more productid will be accquired by same customerid, by same shipvia, on the same day of the week of shipped date. i want the simple query for this.
my tables are from northwind:
[orders] = OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry.
[orders details] = OrderID, ProductID, UnitPrice, Quantity, Discount.
i tried some but it is not exact, it gives wrong result.
select pd.CustomerID,pd.ProductID, pd.no_of_time_purchased, sd.ShipVia, sd.same_ship_count, shipped_day from
select ProductID,o.CustomerID,COUNT(productid) as no_of_time_purchased
from orders o join [Order Details] od on o.OrderID=od.OrderID group by ProductID,o.CustomerID
having count(od.ProductID) >1) pd
join
(select OrderID,customerid, shipvia, count(shipvia)as same_ship_count, DATENAME(DW,ShippedDate)as shipped_day from orders
group by customerid, ShipVia, ShippedDate having COUNT(ShipVia) > 1 ) sd
on sd.CustomerID=pd.CustomerIDHi,
I think I have a solution that will at least give you a clue how to go about it. I have simplified the tables you mentioned and created them as temporary tables on my side, with some fake data to test with. I have incldued the generation of these temporary
tables for your review.
In my example I have included:
1. A customer which has purchased the same product on the same day, using the same ship 3 times,
2. Another example the same as the first but the third purchase was on a different day
3. Another example the same as the first but the third purchase was a different product
4. Another example the same as the first but the third purchase was using a different "ShipVia".
You should be able to see that by grouping on all of the columns that you wich to return, you should not need to perform any subselects.
Please let me know if I have missed any requirements.
Hope this helps:
CREATE TABLE #ORDERS
OrderID INT,
CustomerID INT,
OrderDate DATETIME,
ShipVia VARCHAR(5)
CREATE TABLE #ORDERS_DETAILS
OrderID INT,
ProductID INT,
INSERT INTO #ORDERS
VALUES
(1, 1, GETDATE(), 'ABC'),
(2, 1, GETDATE(), 'ABC'),
(3, 1, GETDATE(), 'ABC'),
(4, 2, GETDATE() - 4, 'DEF'),
(5, 2, GETDATE() - 4, 'DEF'),
(6, 2, GETDATE() - 5, 'DEF'),
(7, 3, GETDATE() - 10, 'GHI'),
(8, 3, GETDATE() - 10, 'GHI'),
(9, 3, GETDATE() - 10, 'GHI'),
(10, 4, GETDATE() - 10, 'JKL'),
(11, 4, GETDATE() - 10, 'JKL'),
(12, 4, GETDATE() - 10, 'MNO')
INSERT INTO #ORDERS_DETAILS
VALUES
(1, 1),
(2, 1),
(3, 1),
(4, 2),
(5, 2),
(6, 2),
(7, 3),
(8, 3),
(9, 4),
(10, 5),
(11, 5),
(12, 5)
SELECT * FROM #ORDERS
SELECT * FROM #ORDERS_DETAILS
SELECT
O.CustomerID,
OD.ProductID,
O.ShipVia,
COUNT(O.ShipVia),
DATENAME(DW, O.OrderDate) AS [Shipped Day]
FROM #ORDERS O
JOIN #ORDERS_DETAILS OD ON O.orderID = OD.OrderID
GROUP BY OD.ProductID, O.CustomerID, O.ShipVia, DATENAME(DW, O.OrderDate) HAVING COUNT(OD.ProductID) > 1
DROP TABLE #ORDERS
DROP TABLE #ORDERS_DETAILS -
ANSI/9i Join Syntax and Pretty Code
I've always tried to keep my SQL statement code formatted in a way that I think helps readability. I picked up the following style because I found it easy to quickly find the FROM clause and the JOINS or conditions:
select e.ename,
e.sal,
d.dname
from emp e,
dept d
* Joins
where e.deptno = d.deptno
* Conditions
and d.dname = 'SALES'
/Of course, for such a simple query I wouldn't have used the comments to divide the WHERE clause into joins and conditions...
Anyway, since Tom Kyte and the 9i documentation suggest using the ANSI join syntax (amongst other reasons), I have decided to begin changing my ways. However, I am having troubles figuring out how to format my SQL to still be "pretty."
For the previous example, a new formatting style seems easy:
select e.ename,
e.sal,
d.dname
from emp e
join dept d on e.deptno = d.deptno
where d.dname = 'SALES'
/Now, when we use an example that has optional joins is where I can't figure what my style should be:
select e.ename,
m.ename as manager
from emp e
left join emp m on e.mgr = m.empno
where e.deptno = 10
/I don't really like this style since it gets so wide, causing problems when indenting for subqueries/inline-views. It also looks kinda clunky because the tables are indented more than everything else...
Anyway, since I don't want to spend a bunch of time figuring out things like style, I'd like to see what other formats people are using. I'd appreciate seeing how others are formatting thier SQL when using the new 9i (old-ANSI) syntax.
Thanks, StanThat looks to me like left aligned (but I may be on the wrong side of the looking glass...)
By preference is to left-align the KEYWORDS and the data words, using indentation to distinguish the start of the different clauses (SELECT, FROM, WHERE, ORDER BY, etc.). This approach is easily standardised with Textpad or similar editing tools. Quite how one programs a text editor to turn one's code into a Rorschach blot is beyond me.
I haven't done much with ANSI joins, so I hadn't come up with a standard for layout. The following is what I think I would do if I ever had to, and is basically an adaption of what I do now ...
FROM user_indexes i
, user_ind_columns ic2
, user_tab_columns c2with the ANSI join stuff indented and aligned. I find rigourous application of UPPER and lower case tends to assist clarity: indentation and alignment are not enough.
SELECT i.table_name
, i.index_name
, ic2.column_position
FROM user_indexes i
INNER JOIN user_ind_columns ic2
ON i.table_name = ic2.table_name
AND i.index_name = ic2.index_name
INNER JOIN user_tab_columns c2
ON ic2.table_name = c2.table_name
AND ic2.column_name = c2.column_name
WHERE i.uniqueness='UNIQUE'
ORDER BY i.table_name
, i.index_name
, ic2.column_position
/ -
Simple Query returns no result
We have a problem with a simple query on a "old" Table in our Database. The Table has following Structure:
CREATE TABLE <table_name>
ROLE_ID INTEGER NOT NULL,
ROLE_NAME VARCHAR (99) ascii NOT NULL,
OBJECTDATA LONG BYTE,
UNIQUE (ROLE_NAME)
The table containts two rows and following querys get these results:
select role_id, role_name from <schema>.<table_name>
--> 2 rows
select role_id, role_name from <schema>.<table_name>
order by role_id
--> 2 rows
select role_id, role_name from <schema>.<table_name>
order by role_name
--> 0 rows ?? confusion
When we create a "new" table with the same structure, and insert the same content to this new table, the queries are working correctly.
What happened with our "old" table, so that these simple queries don't function anymore?
(Database Kernel 7.6.05 Build 009-123-191-997)
thx
gerri
Edited by: Gerfried on Jul 17, 2009 11:42 AMOk, Gerfried send me the dump file and this is what was in it:
INV ROOT/LEAF 15857 perm entries : 0 [block 0]
bottom : 81 filevers: dummy convvers: 9
writecnt: 1
00001 nodepage.pno: 15857 nodepage.pt : data
00006 nodepage.pt2: inv nodepage.chk: checksumData
00008 nodepage.mde: empty
08181 nd_checksum : 61937 nodepge2.pno: 15857
08189 nodepge2.pt : data nodepge2.pt2: inv
08191 nodepge2.chk: checksumData
08192 nodepge2.mde: empty
00009 nd_bottom : 81 nd_rec_cnt : 0
00017 nd_level : 0
00019 nd_filestate: empty
00020 nd_sorted : false nd_root : 15857/F13D0000
00025 nd_right : nil_pno nd_left : nil_pno
00033 nd_last : nil_pno nd_conv_vers: 9
00045 nd_str_vers : nil_pno nd_file_vers: dummy
00052 ndPageVersio: 0 nd_inv_usage: 0
00057 nd_leaf_cnt : 1 nd_treeleavs: nil
00065 nd_trans_id : nil ndInvRoot : nil_pno
00077 nd_write_cnt: 1
END OF FILE
Obviously the reason for not delivering any data for the query is: this index is empty.
See "nd_filestate: empty" !
For some reasons (that I really don't know - sorry about that) this index had not been maintained anymore, since a very long time.
"nd_conv_vers: 9" tells us that it was the 9th savepoint that wrote down this page to the disks and that it had not been touched since then.
To view the current converter version you may just use the db_restartinfo command in dbmcli.
If you were a SAP customer the next thing I'd check would be with which database version these indexes had been created, what the internal file state is etc. - just to figure out the root cause.
As such an analysis is basically not possible via this forum all I can propose is to look for those indexes (containing 0 entries although the table has more rows) and rebuild them.
This statement should do the trick:
select i.owner, i.indexname, i.tablename, if.*
from files if join files tf on if.primaryfileid=tf.fileid
join indexes i on if.fileid=i.fileid
where if.entrycount =0
and if.type ='INDEX'
and tf.entrycount >0
best regards,
Lars -
Sorting: ORDER BY DECODE Problem on Pagination Query
Hi,
I've been searching around the easiest way to perform a dynamic "ORDER BY" clause and the "DECODE()" clause solution seem to be exactly what I am looking for. Unfortunately, It seems the DECODE function is not returning a correct column name value (I think it is returning NULL) since I'm receive the result set as if there was no ORDER BY clause.
I need some help to get through this!
Here the version with DECODE (not working)
It is a Procedure with frstRow, nbRows and var_order as parameters
The output returns the rows as if no ORDER BY was used
SELECT c1, c2
FROM
SELECT ROWNUM rn, arv.*
FROM A_AWA_AR arv
WHERE ROWNUM < (frstRow + nbRows - 1) -- show only some rows determined by procedure
ORDER BY DECODE(var_order, 1, c1, 2, c2, c1) -- sort by var_order
WHERE rn BETWEEN frstRow AND (frstRow + nbRows)
AND ROWNUM <= nbRows
Here the version without DECODE (working)
The output returns the rows as expected - ordered by c2 column
SELECT c1, c2
FROM
SELECT ROWNUM rn, arv.*
FROM A_AWA_AR arv
WHERE ROWNUM < (frstRow + nbRows - 1) -- show only some rows determined by procedure
ORDER BY c2 -- sort by var_order
WHERE rn BETWEEN frstRow AND (frstRow + nbRows)
AND ROWNUM <= nbRows
-----Here are some results I've been getting... I will try the best I can to explain my problem.
And by the way the table A_AWA_AR is a VIEW maybe this can help.
My problem -- I think -- is that I don't understand how DECODE works. I should be a conditional IF-ELSE-THEN-like function but its behavior is not returning what I'm expecting.
I need a solution where I will be able to sort the first lets say 10 rows using ROWNUM to tag row position (in sub-query) then the main query should only show the rows from 3rd postion to 7th position in the main query (as an example) with RN BETWEEN 3 AND 7. My solution does not work when I use decode but works when i pass the column name directly.
Here is a simple query returning the values in the order they are found in the view:
SELECT ROWNUM rn, ROW_ID, SR_NUM
FROM A_AWA_AR
WHERE ROWNUM < 10 Results:
RN ROW_ID SR_NUM
1 1-100876 1-60476802
2 1-10087G 1-60476812
3 1-10087Q 1-60476822
4 1-10088A 1-60476842
5 1-10088K 1-60476852
6 1-10088U 1-60476862
7 1-100894 1-60476872
8 1-10089E 1-60476882
9 1-10089O 1-60476892 Now this is the query & result I would like to obtain (this is done pretty fast since it returns as soon as it reaches 9 sorted rows):
SELECT ROWNUM rn, ROW_ID, SR_NUM
FROM A_AWA_AR
WHERE ROWNUM < 10
ORDER BY SR_NUMResults:
RN ROW_ID SR_NUM
1 1-1RV9J7 1-107274499
2 1-1RVXIF 1-107305575
3 1-1SHY65 1-108332861
4 1-22FOSR 1-125023563
5 1-236F3X 1-126270717
6 1-28P5EB 1-135542675
7 1-29P2VY 1-137219038
8 1-29ZNFH 1-137712221
9 1-2BLWQR 1-140430339 But with decode even a simple pseudo decode:
SELECT ROWNUM rn, ROW_ID, SR_NUM
FROM A_AWA_AR
WHERE ROWNUM < 10
ORDER BY DECODE(1,1,SR_NUM)Results:
RN ROW_ID SR_NUM
1 1-100876 1-60476802
2 1-10087G 1-60476812
3 1-10087Q 1-60476822
4 1-10088A 1-60476842
5 1-10088K 1-60476852
6 1-10088U 1-60476862
7 1-100894 1-60476872
8 1-10089E 1-60476882
9 1-10089O 1-60476892 Here is the structure I'm trying to get and works when passing a column name:
SELECT *
FROM
SELECT ROWNUM rn, ROW_ID, SR_NUM
FROM A_AWA_AR
WHERE ROWNUM < 10
ORDER BY SR_NUM
WHERE rn BETWEEN 3 AND 7Results:
RN ROW_ID SR_NUM
3 1-1SHY65 1-108332861
4 1-22FOSR 1-125023563
5 1-236F3X 1-126270717
6 1-28P5EB 1-135542675
7 1-29P2VY 1-137219038 Now with decode (not working):
SELECT *
FROM
SELECT ROWNUM rn, ROW_ID, SR_NUM
FROM A_AWA_AR
WHERE ROWNUM < 10
ORDER BY DECODE(1,1,SR_NUM)
WHERE rn BETWEEN 3 AND 7Results:
RN ROW_ID SR_NUM
3 1-10087Q 1-60476822
4 1-10088A 1-60476842
5 1-10088K 1-60476852
6 1-10088U 1-60476862
7 1-100894 1-60476872 Thanks for the support! -
Problem using DECODE() function with a Query of Queries
I
posted
on my blog about an issue I was having trying to use the PL/SQL
DECODE() function with a Coldfusion Query of Queries. This function
works fine when you query a database for information. However, when
you query another query, it seems that CF doesn't recognize it. I
got errors stating that it found a left parenthesis where it
expected a FROM key word. Here is a simplified version of what I am
trying to do:
quote:
<!--- Simulated query; similar to what I was calling from
my database --->
<cfscript>
qOriginal = queryNew("Name,Email,CountryCode",
"VarChar,VarChar,VarChar");
newRow = queryAddRow(qOriginal, 5);
querySetCell(qOriginal, "Name", "Joe", 1);
querySetCell(qOriginal, "Email", "[email protected]", 1);
querySetCell(qOriginal, "CountryCode", "AMER", 1);
querySetCell(qOriginal, "Name", "Sally", 2);
querySetCell(qOriginal, "Email", "[email protected]", 2);
querySetCell(qOriginal, "CountryCode", "AMER", 2);
querySetCell(qOriginal, "Name", "Bob", 3);
querySetCell(qOriginal, "Email", "[email protected]", 3);
querySetCell(qOriginal, "CountryCode", "ASIA", 3);
querySetCell(qOriginal, "Name", "Mary", 4);
querySetCell(qOriginal, "Email", "[email protected]", 4);
querySetCell(qOriginal, "CountryCode", "EURO", 4);
querySetCell(qOriginal, "Name", "John", 5);
querySetCell(qOriginal, "Email", "[email protected]", 5);
querySetCell(qOriginal, "CountryCode", "EURO", 5);
</cfscript>
<cfquery name="qCountries" dbtype="query">
SELECT DISTINCT(CountryCode) AS CountryCode,
DECODE(states, "AMER", "North America & Canada",
"EURO", "Europe & Africa", "ASIA", "Japan &
Asia","") CountryName
FROM qOriginal
ORDER BY CountryCode
</cfquery>
<cfdump var="#qCountries#">
<!--- ========== END OF CODE ========== --->
So running this returned the following error:
Query Of Queries syntax error.
Encountered "(. Incorrect Select Statement, Expecting a
'FROM', but encountered '(' instead, A select statement should have
a 'FROM' construct.
Does anybody know why this doesn't work? Is it just not
supported? Please note that I have also tried to use the CASE()
function instead of DECODE() and that resulted in basically the
same error. For now I an looping over my distinct query with a
switch statement and manually loading a new query with the data how
I want it. But it would be a lot cleaner and less code to have the
DECODE() to work. Thx!DECODE() is an Oracle function, not generic SQL. Q-of-Q is a
very limited subset of SQL and lacks many functions and clauses
available in standard SQL, especially what you may be used to using
in your particular RDBMS.
See
Query
of Queries user guide
Phil -
How to write a simple query.
I have a table where I have data shown below. Now, I want to write a simple query which lists me the project and the count of the distinct effective dates for which data is existant there.
Sample data:
Project Task Effective Date (xx_proj_task_data)
101 T1 01-Jan-2008
101 T1 01-Feb-2008
101 T1 01-Mar-2008
101 T2 01-Jan-2008
101 T2 01-Apr-2008
101 T3 01-Apr-2008
102 T1 01-Jan-2008
102 T1 01-Feb-2008
102 T2 01-Apr-2008
103 T1 01-Jan-2008
103 T1 01-Feb-2008
103 T1 01-Mar-2008
103 T1 01-Apr-2008
103 T2 01-May-2008
103 T3 01-Jun-2008
103 T1 01-Jan-2008
103 T1 01-Aug-2008
103 T2 01-Apr-2008
Output Reqd:
Project Count(Distinct Effective Dates)
101 4
102 3
103 7
I can write a query that says:
select project_id, count(1)
from (select distinct project_id, effective_date
from xx_proj_task_data) x
group by project_id;
But, is there a way I can achieve the same by avoiding the inner Query (x) and just by a simple query ?
Thanks!Try below query:
select project_id
, count(distinct effective_date)
from xx_proj_task_data
group by project_id;
--venkata
Maybe you are looking for
-
Itunes not opening on windows 8
Recently i just bought the Ipodtouch 4g like today and to have it work i have to connect it into itunes. I have itunes already installed into my laptop and has worked properly before, but it has choosen today to just not choose to open. There is n
-
I would like to buy a new Mac but not sure if I should go with the Mac mini or iMac. I will use it to edit home videos and surf the web. I was going to either get a 1.66GHz Mac mini with 1GB ram and hook it up to my HDTV or the 17" iMac with 1GB ram.
-
Floating-point numbers: min value
Hi, the number wrapper classes each define a MAX_VALUE and a MIN_VALUE constant. While the MIN_VALUE of non-floating point numbers are negative numbers, the MIN_VALUE of the floating point numbers are the smallest postive numbers. From the Javadoc: F
-
HT4009 app glitched and then I have a 100 in app purchase
I don't get it. App froze and tapped screen several times. Pressed home button. Restarted app and "thank you for your purchase" shows up with a 99 dollar charge. Clash of Clans in app purchase
-
IRecruitment new Functionality in R12.1
Can anyone share a Presentation of the coming new functionality in iRecruitment release 12.1? Thanks