SQL Optimization with join and in subselect
Hello,
I am having problems finding a way to optimize a query that has a join from a fact table to several dimension tables (star schema) and a constraint defined as an in (select ....). I am hoping that this constraint will filter the fact table then perform the joins but I am seeing just the opposite with the optimizer joining first and then filtering at the very end. I am using the cost optimizer and saw that it does in subselects last in the predicate order. I tried the push_subq hint with no success.
Does anyone have any other suggestions?
Thanks in advance,
David
example sql:
select ....
from fact, dim1, dim2, .... dim <n>
where
fact.dim1_fk in ( select pf from dim1 where code = '10' )
and fact.dim1_fk = dim1.pk
and fact.dim2_fk = dim2.pk
and fact.dim<n>_fk = dim<n>.pk
The original query probably shouldn't use the IN clause because in this example it is not necessary. There is no limit on the values returned if a sub-select is used, the limit is only an issue with hard coded literals like
.. in (1, 2, 3, 4 ...)Something like this is okay even in 8.1.7
SQL> select count(*) from all_objects
2 where object_id in
3 (select object_id from all_objects);
COUNT(*)
32378The IN clause has its uses and performs better than EXISTS in some conditions. Blanket statements to avoid IN and use EXISTS instead are just nonsense.
Martin
Similar Messages
-
Need complex query with joins and AGGREGATE functions.
Hello Everyone ;
Good Morning to all ;
I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
I want to make complex join with AGGREGATE FUNCTION.
my table details
SQL> select from tab;*
TNAME TABTYPE CLUSTERID
DEPT TABLE
PAYROLL TABLE
EMP TABLE
SQL> desc emp
Name
EID
ENAME
EDOB
EGENDER
EQUAL
EGRADUATION
EDESIGNATION
ELEVEL
EDOMAIN_ID
EMOB_NO
SQL> desc dept
Name
EID
DNAME
DMANAGER
DCONTACT_NO
DPROJ_NAME
SQL> desc payroll
Name
EID
PF_NO
SAL_ACC_NO
SALARY
BONUS
I want to make complex query with joins and AGGREGATE functions.
Dept names are : IT , ITES , Accounts , Mgmt , Hr
GRADUATIONS are : Engineering , Arts , Accounts , business_applications
I want to select records who are working in IT and ITES and graduation should be "Engineering"
salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
Please help me to make a such complex query with joins ..
Thanks in advance ..
Edited by: 969352 on May 25, 2013 11:34 AM969352 wrote:
why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
My Goal is :
1. When executing my own query i need to check expalin plan.please proceed to do so
http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
Best Wishes on your quest for performance improvements. -
Dear Sir/Madam
I'm a student who is interested in Oracle Database and
I have some problems with JOIN and Sub-query.
I hope so many of you could help me.
if i use JOIN without sub-query, may it be faster or not?
SELECT field1, field2 FROM tableA INNER JOIN tableB
if i use JOIN with sub-query, may it be faster or not?
SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
Thanks in advance!Hi,
fac30d8e-74d3-42aa-b643-e30a3780e00f wrote:
Dear Sir/Madam
I'm a student who is interested in Oracle Database and
I have some problems with JOIN and Sub-query.
I hope so many of you could help me.
if i use JOIN without sub-query, may it be faster or not?
SELECT field1, field2 FROM tableA INNER JOIN tableB
if i use JOIN with sub-query, may it be faster or not?
SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
Thanks in advance!
As the others have said, the execution plan will give you a better idea about which is faster.
If you're trying to see how using (or not using) a sub-query affects performance, make the rest of the queries as similar as possible. For example, include field3 in both queries, or ignore field3 in both queries.
In this particular case, I guess the optimizer would do the same thing either way, but that's just a guess. I can't see your execution plans.
In general, simpler code is faster, and better in other ways, too. In this case
tableB
is simpler than
(SELECT field1, field2 FROM tableB)
Why do you want a sub-query in this example? -
Need help in optimizing the query with joins and group by clause
I am having problem in executing the query below.. it is taking lot of time. To simplify, I have added the two tables FILE_STATUS = stores the file load details and COMM table that is actual business commission table showing records successfully processed and which records were transmitted to other system. Records with status = T is trasnmitted to other system and traansactions with P is pending.
CREATE TABLE FILE_STATUS
(FILE_ID VARCHAR2(14),
FILE_NAME VARCHAR2(20),
CARR_CD VARCHAR2(5),
TOT_REC NUMBER,
TOT_SUCC NUMBER);
CREATE TABLE COMM
(SRC_FILE_ID VARCHAR2(14),
REC_ID NUMBER,
STATUS CHAR(1));
INSERT INTO FILE_STATUS VALUES ('12345678', 'CM_LIBM.TXT', 'LIBM', 5, 4);
INSERT INTO FILE_STATUS VALUES ('12345679', 'CM_HIPNT.TXT', 'HIPNT', 4, 0);
INSERT INTO COMM VALUES ('12345678', 1, 'T');
INSERT INTO COMM VALUES ('12345678', 3, 'T');
INSERT INTO COMM VALUES ('12345678', 4, 'P');
INSERT INTO COMM VALUES ('12345678', 5, 'P');
COMMIT;Here is the query that I wrote to give me the details of the file that has been loaded into the system. It reads the file status and commission table to show file name, total records loaded, total records successfully loaded to the commission table and number of records that has been finally transmitted (status=T) to other systems.
SELECT
FS.CARR_CD
,FS.FILE_NAME
,FS.FILE_ID
,FS.TOT_REC
,FS.TOT_SUCC
,NVL(C.TOT_TRANS, 0) TOT_TRANS
FROM FILE_STATUS FS
LEFT JOIN
SELECT SRC_FILE_ID, COUNT(*) TOT_TRANS
FROM COMM
WHERE STATUS = 'T'
GROUP BY SRC_FILE_ID
) C ON C.SRC_FILE_ID = FS.FILE_ID
WHERE FILE_ID = '12345678';In production this query has more joins and is taking lot of time to process.. the main culprit for me is the join on COMM table to get the count of number of transactions transmitted. Please can you give me tips to optimize this query to get results faster? Do I need to remove group and use partition or something else. Please help!I get 2 rows if I use my query with your new criteria. Did you commit the record if you are using a second connection to query? Did you remove the criteria for file_id?
select carr_cd, file_name, file_id, tot_rec, tot_succ, tot_trans
from (select fs.carr_cd,
fs.file_name,
fs.file_id,
fs.tot_rec,
fs.tot_succ,
count(case
when c.status = 'T' then
1
else
null
end) over(partition by c.src_file_id) tot_trans,
row_number() over(partition by c.src_file_id order by null) rn
from file_status fs
left join comm c
on c.src_file_id = fs.file_id
where carr_cd = 'LIBM')
where rn = 1;
CARR_CD FILE_NAME FILE_ID TOT_REC TOT_SUCC TOT_TRANS
LIBM CM_LIBM.TXT 12345678 5 4 2
LIBM CM_LIBM.TXT 12345677 10 0 0Using RANK can potentially produce multiple rows to be returned though your data may prevent this. ROW_NUMBER will always prevent duplicates. The ordering of the analytical function is irrelevant in your query if you use ROW_NUMBER. You can remove the outermost query and inspect the data returned by the inner query;
select fs.carr_cd,
fs.file_name,
fs.file_id,
fs.tot_rec,
fs.tot_succ,
count(case
when c.status = 'T' then
1
else
null
end) over(partition by c.src_file_id) tot_trans,
row_number() over(partition by c.src_file_id order by null) rn
from file_status fs
left join comm c
on c.src_file_id = fs.file_id
where carr_cd = 'LIBM';
CARR_CD FILE_NAME FILE_ID TOT_REC TOT_SUCC TOT_TRANS RN
LIBM CM_LIBM.TXT 12345678 5 4 2 1
LIBM CM_LIBM.TXT 12345678 5 4 2 2
LIBM CM_LIBM.TXT 12345678 5 4 2 3
LIBM CM_LIBM.TXT 12345678 5 4 2 4
LIBM CM_LIBM.TXT 12345677 10 0 0 1 -
EA1 - SQL Formatter issues (JOINs and GROUPs and ORDER BY oh my ;)
Great job with improving the SQL Formatter, but it still has some bugs that need to be worked out.
The key words JOIN and it's modifiers INNER, LEFT, RIGHT and FULL OUTER are not recognized as master key words. As such they end up flush against the left margin Also when GROUP BY and/or ORDER BY key words are present in an outer most select statement the other key words are not indented far enough to be right aligned with the end of the word BY and are indented too far to be right aligned with the word GROUP or ORDER. In sub queries, GROUP and ORDER BY are correctly right aligned with their respective SELECT statements.We're picking up and collating the Formatter issues. I'll add these.
Specific bug for these #7013462
Sue -
SQL query with JSP and WML-parameters
Hey,
Could you help me?
I'm trying to do the following. WML deck card 1 send parameter to same WML deck's card help. I try to read the parameter with JSP in card help by putting the parameter to SQL query, but it doesn't work. I can read the parameter with WML in card help. I can also print the value of the parameter with JSP if I generate WML with JSP.
/*parameter sending from card 1 to card help*/
out.println("<go href='#helpcard'>");
out.println("<setvar name='valittukurssi' value='$(valittukurssi)'/>");
/*parameter read with WML in card help */
<p>Valitse kurssi.
$valittukurssi</p>
/'parameter read with JSP by generating WML with JSP*/
out.println("<p>$valittukurssi</p>");
/* SQL query with JSP */
ResultSet uudettulokset = uusilause.executeQuery("select * from kurssi where lyhenne='$valittukurssi'");
Thanks,
RampeYou're problem is easy to fix. You're confusing WML variables with JSP variables. See below:
>
/*parameter sending from card 1 to card help*/
out.println("<go href='#helpcard'>");
out.println("<setvar name='valittukurssi'
value='$(valittukurssi)'/>");
Above you set a var that will work on the phone, not in JSP.
/*parameter read with WML in card help */
<p>Valitse kurssi.
$valittukurssi</p>
Yes the above does display the parameter, because it is a client side WML var, but you cannot use this variable in the JSP code (that's why your SWL fails).
/'parameter read with JSP by generating WML with
JSP*/
out.println("<p>$valittukurssi</p>");Here's you're problem, the above line is EXACTLY the same as the one before it. When the container parses through this JSP code it translates the above line to:
<p>$valittukurssi</p> on the WML page and the CLIENT uses it's local variable to display it.
What you need and want is to have a variable that can be used in JSP code and output to your WML page. Here's how it's done:
out.println("<go href='#helpcard'>");
String some_name = "valittukurssi";
out.println("<setvar name='"+some_name+"'
value='$("+some_name+")'/>");
//note that you may have to escape the ( and ) with a \
//so we displayed the variable above into the WML page, now we can use it in the SQL query:
/* SQL query with JSP */
ResultSet uudettulokset =
uusilause.executeQuery("select * from kurssi where
lyhenne='"+some_name+"'");//the end of the command is: " ' " ) ;
Frank Krul
Got Node? -
Materialized View with Joins and Possibilities of Partitioning
Hi,
We have a materialized view which has a data to query around 12 gb. The query goes some thing like
this.
Select a.c1,a.c2,b.c1,b.c2,c.c1,c.c2
from a,b,c
where a.c1=b.c1
--and the where condition goes on...
--i.e Basically joining 3 different tables with complex join conditions but without any group functions and subqueries.
Now i have few questions here.
Firstly as the Mview is created with joins we will have to create separate logs for each tables and we have did the same. The logs are created with rowid and sequence for better performance during refresh.
Question No 1
Is this is a best approach for materializing a query with complex join conditions. Or Is it better to make 3 different materialized views for each 3 tables and join those 3 MViews and write a query for my report. I ask this question just to make sure the refresh time is brought down by this method. But as such as we have created 3 different logs for 3 tables the refresh must be happening separately.
Question No 2
Data is likely to grow faster and faster on this. So we have a idea of making this a partitioned Mview. Can the Pro's advice me on this and suggest me the right practice for the same and help me to correct links from where i can pick a example and continue from there.
Question No 3
How to find whether the materialized view has refreshed on a fast mode or complete mode after the last refresh.
Apart from querying and checking the rowid which i feel is quiet cumbersome for a mview with a data volume like what we have. By default when i see the info in TOAD for this Mview it shows Refresh Mode as "Force". But how to ascertain this.
Thanks in anticipation for a good round of discussionHi,
We have a materialized view which has a data to query around 12 gb. The query goes some thing like
this.
Select a.c1,a.c2,b.c1,b.c2,c.c1,c.c2
from a,b,c
where a.c1=b.c1
--and the where condition goes on...
--i.e Basically joining 3 different tables with complex join conditions but without any group functions and subqueries.
Now i have few questions here.
Firstly as the Mview is created with joins we will have to create separate logs for each tables and we have did the same. The logs are created with rowid and sequence for better performance during refresh.
Question No 1
Is this is a best approach for materializing a query with complex join conditions. Or Is it better to make 3 different materialized views for each 3 tables and join those 3 MViews and write a query for my report. I ask this question just to make sure the refresh time is brought down by this method. But as such as we have created 3 different logs for 3 tables the refresh must be happening separately.
Question No 2
Data is likely to grow faster and faster on this. So we have a idea of making this a partitioned Mview. Can the Pro's advice me on this and suggest me the right practice for the same and help me to correct links from where i can pick a example and continue from there.
Question No 3
How to find whether the materialized view has refreshed on a fast mode or complete mode after the last refresh.
Apart from querying and checking the rowid which i feel is quiet cumbersome for a mview with a data volume like what we have. By default when i see the info in TOAD for this Mview it shows Refresh Mode as "Force". But how to ascertain this.
Thanks in anticipation for a good round of discussion -
Sql query with conditions and calculations???
Hi,
how I can build a query with conditions and calculations?
E.g. I've got this table
Start | End | Working Place | Mandatory
01-JAN-13 | 11-JAN-13 | Office | 1
14-JAN-13 | 25-JAN-13 | Home Office | 0
04-MRZ-13| 15-MRZ-13 | Office | 0
11-FEB-13 | 22-FEB-13 | Office | 1
Now if column working place=Office and column mandatory=0
the new column "price" has to calculate: (End-Start)* $25.00
and if working place=Office and column mandatory=1
the "price" column has to calculate: (End-Start)* $20.60
else $0.00
I tried it with the case statement but I didn't know how
to calculate my values and display it to the virtual column "price".
Something like
case
when Working_Place = 'Office' and Mandatory=1
then ...
else '0.00'
end as PRICE
Or is it not possible?
Edited by: DB2000 on 12.03.2013 05:09Use CASE:
select start_dt,
end_dt,
working_place,
mandatory,
case
when working_place = 'Office' and mandatory = 0 then (end_dt - start_dt) * 25
when working_place = 'Office' and mandatory = 1 then (end_dt - start_dt) * 20.60
else 0
end price
from tbl
START_DT END_DT WORKING_PLA MANDATORY PRICE
01-JAN-13 11-JAN-13 Office 1 206
14-JAN-13 25-JAN-13 Home Office 0 0
04-MAR-13 15-MAR-13 Office 0 275
11-FEB-13 22-FEB-13 Office 1 226.6
SQL> SY. -
SQL statement with LIMIT and total count?
Hello,
I would like to know if it is possible to execute a single SQL statement that will return me a subset of data (for pagination purposes) that not only includes the subset of data for the page but the count of all available data. Can this be done so as to not take up the cpu and time it takes to essentially run two queries? One to get the subset and one to get the count? I think simply doing a subselect is not going to give me what I want in that we actually query twice.
There may be no way to do this other than that, but I wanted to check with the gurus here first. :)
Thanks,
Markselect *
from (
select i.*,
row_number() over(order by i) rn, -- used for
pagination
count(*) over(partition by 1) cnt -- total count
of rows found for this search
from mytable
where < PUT ALL LIMITING (i.e., "search") CONDITIONS
HERE >
where rn between 41 and 50 -- pagination clauseNice one
BUT of course it adds additional row in execution plan and takes additional time and CPU :)
I assume that it directly depends of course on returned result set and some other factors like available sort space but a simple test case on a table big which actually is 1.6 M rows like dba_source got following results:
here is the first one returning also count(*)
SQL> select *
2 from (
3 select i.*,
4 row_number() over(order by owner, name, type) rn
5 , -- used for pagination
6 count(*) over(partition by 1) cnt -- total count of rows found for this search
7 from big i
8 where owner like 'S%' and name like '%A%'
9 )
10 where rn between 41 and 45
11 /
OWNER NAME TYPE
LINE
TEXT
RN CNT
SYS ANYDATA TYPE
13
STATIC FUNCTION ConvertVarchar(c IN VARCHAR) return AnyData,
41 999744
SYS ANYDATA TYPE
11
STATIC FUNCTION ConvertDate(dat IN DATE) return AnyData,
42 999744
SYS ANYDATA TYPE
9
43 999744
SYS ANYDATA TYPE
7
They serve as explicit CAST functions from any type in the Oracle ORDBMS
44 999744
SYS ANYDATA TYPE
6
enable construction of the AnyData in its entirity with a single call.
45 999744
Elapsed: 00:00:41.02
SQL> ed
Wrote file afiedt.buf
1 select n.name, m.value from v$statname n, v$mystat m
2 where n.statistic# = m.statistic#
3* and (upper(name) like '%SORT%' or upper(name) like '%TEMP%')
SQL> /
NAME VALUE
physical reads direct temporary tablespace 35446
physical writes direct temporary tablespace 17723
RowCR attempts 0
SMON posted for dropping temp segment 0
sorts (memory) 36
sorts (disk) 1
sorts (rows) 1999596
OTC commit optimization attempts 0
8 rows selected.here is the second one returning only rows:
SQL> ed
Wrote file afiedt.buf
1 select *
2 from (
3 select i.*,
4 row_number() over(order by owner, name, type) rn
5 --, -- used for pagination
6 -- count(*) over(partition by 1) cnt -- total count of rows found for this search
7 from big i
8 where owner like 'S%' and name like '%A%'
9 )
10* where rn between 41 and 45
SQL> /
OWNER NAME TYPE
LINE
TEXT
RN
SYS ANYDATA TYPE
13
STATIC FUNCTION ConvertVarchar(c IN VARCHAR) return AnyData,
41
SYS ANYDATA TYPE
11
STATIC FUNCTION ConvertDate(dat IN DATE) return AnyData,
42
SYS ANYDATA TYPE
9
43
SYS ANYDATA TYPE
7
They serve as explicit CAST functions from any type in the Oracle ORDBMS
44
SYS ANYDATA TYPE
6
enable construction of the AnyData in its entirity with a single call.
45
Elapsed: 00:00:12.09
SQL> select n.name, m.value from v$statname n, v$mystat m
2 where n.statistic# = m.statistic#
3 and (upper(name) like '%SORT%' or upper(name) like '%TEMP%')
4 /
NAME VALUE
physical reads direct temporary tablespace 0
physical writes direct temporary tablespace 0
RowCR attempts 0
SMON posted for dropping temp segment 0
sorts (memory) 10
sorts (disk) 0
sorts (rows) 999812
OTC commit optimization attempts 0
8 rows selected.So execution time 41 sec vs 12 sec
sorts (rows) 1 999 596 vs 999 812
physical reads/writes direct temporary tablespace 35446/17723 vs 0/0
I assume that for a small overall returned row count it probably is OK, but for less restrictive search it can be quite deadly as before with two queries.
Gints Plivna
http://www.gplivna.eu -
Tuning SQL query with SDO and Contains?
I'trying to optimize a query
with a sdo_filter and an intermedia_contains
on a 3.000.000 records table,
the query look like this
SELECT COUNT(*) FROM professionnel WHERE mdsys.sdo_filter(professionnel.coor_cart,mdsys.sdo_geometry(2003, null, null,mdsys.sdo_elem_info_array(1,1003,4),mdsys.sdo_ordinate_array(809990,2087279,778784,2087279,794387,2102882)),'querytype=window') = 'TRUE' AND professionnel.code_rubr ='12 3 30' AND CONTAINS(professionnel.Ctx,'PLOMBERIE within Nom and ( RUE within Adresse1 )',1)>0
and it takes 15s on a bi 750 pentium III with
1.5Go of memory running under 8.1.6 linux.
What can i do to improve this query time?
nullHi Vincent,
We have patches for Oracle 8.1.6 Spatial
on NT and Solaris.
These patches include bug fixes and
performance enhancements.
We are in the process of making these patches
avaialble in a permanent place, but until then, I will temporarily put the patches on:
ftp://oracle-ftp.oracle.com/
Log in as anonymous and use your email for
password.
The patches are in /tmp/outgoing in:
NT816-000706.zip - NT patch
libordsdo.tar - Solaris patch
I recommend doing some analysis on
individual pieces of the query.
i.e. time the following:
1)
SELECT COUNT(*)
FROM professionnel
WHERE mdsys.sdo_filter(
professionnel.coor_cart,
mdsys.sdo_geometry(
2003, null, null,
mdsys.sdo_elem_info_array(1,1003,4),
mdsys.sdo_ordinate_array(
809990,2087279,
778784,2087279,
794387,2102882)),
'querytype=window') = 'TRUE';
2)
SELECT COUNT(*)
FROM professionnel
WHERE CONTAINS(professionnel.Ctx,
'PLOMBERIE within Nom and ( RUE within Adresse1)',1) >0;
You might want to try reorganizing the entire
query as follows (no promises).
If you contact me directly, I can try to
help to further tune the SQL.
Hope this helps. Thanks.
Dan
select count(*)
FROM
(SELECT /*+ no_merge */ rowid
FROM professionnel
WHERE mdsys.sdo_filter(
professionnel.coor_cart,
mdsys.sdo_geometry(
2003, null, null,
mdsys.sdo_elem_info_array(1,1003,4),
mdsys.sdo_ordinate_array(809990,2087279,
778784,2087279,
794387,2102882)),
'querytype=window') = 'TRUE'
) a,
(SELECT /*+ no_merge */ rowid
FROM professionnel
WHERE CONTAINS(professionnel.Ctx,
'PLOMBERIE within Nom and
( RUE within Adresse1)',1) >0
) b
where a.rowid = b.rowid
and professionnel.code_rubr ='12 3 30';
**NOTE** Try this with no index on code_rubr
null -
Hello All,
I'm trying to update several colums of a table from a inner join query.
First a retrieve the rows afected and the values that I need for the update (I call this subquery ED_Query).
It's important to note that this subquery has a group by and and having clause.
My first attemp (using the query that work in SQL Server query) fails:
SQL> update ED_Update
2 set ED_Update.dtHoraInicioReal = ED_Query.dtHoraInicioReal,
3 ED_Update.dtHoraFinReal = ED_Query.dtHoraFinReal,
4 ED_Update.fPorcentajeRealizado = ED_Query.fPorcentajeRealizado
5 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED_Update
6 inner join (
7 select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
8 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
9 MAX(HPP.iOrden) as iOrdenUltimaParada,
10 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
11 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
12 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado
13 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
14 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
15 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
16 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
17 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
18 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal
19 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
20 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal)
21 ) ED_Query
22 on ED_Update.iIdExpedicionDiaria = ED_Query.iIdExpedicionDiaria;
ERROR at line 5:
ORA-00933: SQL command not properly ended
The subquery (ED_Query) work fine in Oracle, so I suspect that the problems are when I mix it with the update clause.
SQL> select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
2 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
3 MAX(HPP.iOrden) as iOrdenUltimaParada,
4 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
5 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
6 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado,
7 ED.dtHoraInicioReal as ED_dtHoraInicioReal, ED.dtHoraFinReal as ED_dtHoraFinReal, ED.fPorcentajeRealizado as ED_fPorcentajeRealizado
8 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
9 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
10 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
11 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
12 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
13 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal, ED.fPorcentajeRealizado
14 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
15 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal);
IIDEXPEDICION IIDEXPEDICIONDIARIA INUMPARADAS IORDENULTIMAPARADA DTHORAINI
DTHORAFIN FPORCENTAJEREALIZADO ED_DTHORA ED_DTHORA ED_FPORCENTAJEREALIZADO
-131076 5662 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
-131076 5663 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
-131076 5664 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
After reading this forum, I change the query and try the next one:
SQL> UPDATE
2 (
3 select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
4 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
5 MAX(HPP.iOrden) as iOrdenUltimaParada,
6 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
7 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
8 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado,
9 ED.dtHoraInicioReal as ED_dtHoraInicioReal, ED.dtHoraFinReal as ED_dtHoraFinReal, ED.fPorcentajeRealizado as ED_fPorcentajeRealizado
10 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
11 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
12 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
13 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
14 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
15 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal,ED.dtHoraFinReal, ED.fPorcentajeRealizado
16 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
17 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal)
18 )
19 SET ED_dtHoraInicioReal = dtHoraInicioReal,
20 ED_dtHoraFinReal = dtHoraFinReal,
21 ED_fPorcentajeRealizado = fPorcentajeRealizado;
ERROR at line 2:
ORA-01732: data manipulation operation not legal on this view
Some help?
Thanl in advance.
Edited by: 984483 on 28-ene-2013 1:48Thanks for your answer. I tried to rewrite my question.
SQL> select * from v$version;
BANNER
Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
PL/SQL Release 9.2.0.3.0 - Production
CORE 9.2.0.3.0 Production
TNS for 32-bit Windows: Version 9.2.0.3.0 - Production
NLSRTL Version 9.2.0.3.0 - Production
I have 2 tables. I like to update one of them (ED_Update) with the data from the another one (ED_Query).
This example is equivalent:
create table ED_Query (id number,
date01 date,
number01 number)
insert into ED_Query values (1, to_date('01/01/2013','DD/MM/YYYY'), 10);
insert into ED_Query values (2, to_date('01/01/2013','DD/MM/YYYY'), 20);
insert into ED_Query values (3, to_date('01/01/2013','DD/MM/YYYY'), 30);
insert into ED_Query values (4, to_date('02/01/2013','DD/MM/YYYY'), 40);
insert into ED_Query values (5, to_date('03/01/2013','DD/MM/YYYY'), 50);
create table ED_Update (date01 date,
numberMax number,
numberSum number)
insert into ED_Update values (to_date('01/01/2013','DD/MM/YYYY'), 0, 0);
insert into ED_Update values (to_date('02/01/2013','DD/MM/YYYY'), 0, 0);
insert into ED_Update values (to_date('03/01/2013','DD/MM/YYYY'), 0, 0);
The next update query fails with ORA-00933: SQL command not properly ended.
update ED_Update
set ED_Update.date01 = ED_Query.date01,
ED_Update.numberMax = ED_Query.numberMax,
ED_Update.numberSum = ED_Query.numberSum
inner join
select date01, max (number01) as numberMax, sum(number01) as numberSum
from ED_Query
where date01 = TO_DATE('01/01/2013', 'DD/MM/YYYY')
group by date01
) ED_Query
on ED_Update.date01 = ED_Query.date01
I think the problem is in the update clause because the next query work:
select * from
ED_Update
inner join
select date01, max (number01) as numberMax, sum(number01) as numberSum
from ED_Query
where date01 = TO_DATE('01/01/2013', 'DD/MM/YYYY')
group by date01
) ED_Query
on ED_Update.date01 = ED_Query.date01
Thank in advance. -
Tune the query with join and not exists
This is on 10g R2.
I have a query similar to :
Select A.*, C.*
From A inner join B on A.id = B.id
Left join C on A.kid = C.kid
Where not exists
(select * from D where A.fid = D.fid and A.stat = 2);
I want avoiding to use the NOT EXISTS in the last part of the query
I tried the autotrace explain of above and compared with others format and found no better execution plan than that. The explain plan indicated that there were long "table access full" operation on B, due to its little huge records, and a long operation of the "NESTED LOOPS OUTER". I had tried to replace the NOT EXISTS part with another LEFT JOIN in the FROM, but it went worse. So Anyone can suggest a better way? or it is the most efficient query I can get?Here is the tkprof output
from baandb.ttfacr200201 a
inner join baandb.ttfgld106201 c on (a.t$ttyp = c.t$otyp and a.t$ninv = c.t$odoc) and c.t$leac like :"SYS_B_0"
left join baandb.ttfgld910201 d on c.t$dim2 = d.t$dimx and d.t$dtyp = :"SYS_B_1"
where not exists
(select * from baandb.tcisli205201 b
where a.t$ttyp = b.t$ityp and a.t$ninv = b.t$idoc)
and (a.t$trec = :"SYS_B_2" or a.t$trec = :"SYS_B_3" and t$tdoc = :"SYS_B_4")
call count cpu elapsed disk query current rows
Parse 1 0.00 0.00 0 0 0 0
Execute 1 0.01 0.01 0 0 0 0
Fetch 5 1.06 52.11 29925 45943 0 54
total 7 1.07 52.12 29925 45943 0 54
Misses in library cache during parse: 1
Misses in library cache during execute: 1
Optimizer mode: ALL_ROWS
Parsing user id: 31
Rows Row Source Operation
54 HASH JOIN RIGHT ANTI (cr=45943 pr=29925 pw=0 time=2317005 us)
9957 INDEX FAST FULL SCAN TCISLI205201$IDX1 (cr=39 pr=0 pw=0 time=54 us)(object id 16639)
10067 NESTED LOOPS OUTER (cr=45904 pr=29925 pw=0 time=68531937 us)
10067 HASH JOIN (cr=35837 pr=29925 pw=0 time=68471521 us)
10420 TABLE ACCESS FULL TTFACR200201 (cr=2424 pr=0 pw=0 time=20894 us)
33156 TABLE ACCESS FULL TTFGLD106201 (cr=33413 pr=29925 pw=0 time=117767552 us)
51 INDEX UNIQUE SCAN TTFGLD910201$IDX1 (cr=10067 pr=0 pw=0 time=53177 us)(object id 20402)
OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 2 0.00 0.00 0 0 0 0
Execute 3 0.02 0.02 0 0 0 0
Fetch 6 1.06 52.11 29925 45943 0 55
total 11 1.08 52.14 29925 45943 0 55 -
Oracle UPDATE syntax with JOIN and WHERE clause
I need to update one of my tables, and can't seem to get the syntax right. I've tried a 4 different approaches, but not having any luck. Any help would be greatly appreciated.
Attempt #1: Error: SQL command not properly ended
UPDATE TESTDTA.F4941
SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM
FROM TESTDTA.F4941
INNER JOIN TESTDTA.F4981
ON TESTDTA.F4941.RSSHPN = TESTDTA.F4981.FHSHPN
WHERE TESTDTA.F4941.RSSHPN = 647143
AND TESTDTA.F4941.RSDSTN = 0
AND TESTDTA.F4941.RSADDJ > 110365
AND TESTDTA.F4981.FHCGC1 = 'DIS';
Attempt #2: Error report: SQL Error: ORA-00904: "TESTDTA"."F4981"."FHUOM": invalid identifier 00904. 00000 - "%s: invalid identifier"
UPDATE (SELECT TESTDTA.F4941
FROM TESTDTA.F4941
INNER JOIN TESTDTA.F4981
ON TESTDTA.F4941.RSSHPN = TESTDTA.F4981.FHSHPN
WHERE TESTDTA.F4941.RSSHPN = 647143
AND TESTDTA.F4941.RSDSTN = 0
AND TESTDTA.F4941.RSADDJ > 110365
AND TESTDTA.F4981.FHCGC1 = 'DIS')
SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM
Attempt #3: Error report: SQL Error: ORA-00904: "TESTDTA"."F4941": invalid identifier 00904. 00000 - "%s: invalid identifier"
UPDATE (SELECT *
FROM TESTDTA.F4941
INNER JOIN TESTDTA.F4981
ON TESTDTA.F4941.RSSHPN = TESTDTA.F4981.FHSHPN
WHERE TESTDTA.F4941.RSSHPN = 647143
AND TESTDTA.F4941.RSDSTN = 0
AND TESTDTA.F4941.RSADDJ > 110365
AND TESTDTA.F4981.FHCGC1 = 'DIS')
SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM;
Attempt #4: Error: ORA-00925: missing INTO keyword 00925. 00000 - "missing INTO keyword"
MERGE TESTDTA.F4941
USING TESTDTA.F4981
ON (TESTDTA.F4941.RSSHPN = TESTDTA.F4981.FHSHPN
AND TESTDTA.F4941.RSSHPN = 647143
AND TESTDTA.F4941.RSDSTN = 0
AND TESTDTA.F4941.RSADDJ > 110365
AND TESTDTA.F4981.FHCGC1 = 'DIS'
WHEN MATCHED THEN
UPDATE SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ
,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM;thank you for the attempt, but I get this error trying your method...
Error report:
SQL Error: ORA-01779: cannot modify a column which maps to a non key-preserved table
01779. 00000 - "cannot modify a column which maps to a non key-preserved table"
*Cause: An attempt was made to insert or update columns of a join view which
map to a non-key-preserved table.
*Action: Modify the underlying base tables directly.
as for the background of what I'm trying to...
I have 2 tables, one that has shipments with no miles (F4941 / Routing Steps), and another that does have miles (F4981 / Freight Audit History).
I want to update the miles & UnitOfMeasure columns for all shipments in the F4941 that currently have 0 miles with the miles found in the F4981 which are connected by Shipment number. Here's my same script, with simpler naming.
UPDATE RoutingSteps
SET RoutingSteps.Miles=FreightAuditHistory.Miles,RoutingSteps.UnitOfMeasure=FreightAuditHistory.UnitOfMeasure
FROM RoutingSteps
INNER JOIN FreightAuditHistory
ON RoutingSteps.ShipmentNumber = FreightAuditHistory.ShipmentNumber
WHERE RoutingSteps.ShipmentNumber = 647143
AND RoutingSteps.Miles = 0
AND RoutingSteps.ShipmentDate > 110365
AND FreightAuditHistory.Category = 'DIS';
hope this helps visualize my intent -
SQL Injection with CF7 and MS SQL 2005
I looked through a bunch of SQL injection posts and couldn't
find a definitive answer to this...
Let me introduce this by saying that I know I should be using
CFQUERYPARAM with EVERY CF variable in a CFQUERY tag. No excuses.
But for a necessary quick fix, if I only use it for numeric
DB fields, is SQL injection still possible (using MS SQL 2005)?
I've yet to successfully perform SQL injection while manipulating a
variable surrounded by single quotes in the query.
Scenario 1) select * from users where user_id=#form.user_id#
...is a gimme to hack, but
Scenario 2) select * from users where
password='#form.password#' ...is another story
Has anyone ever heard of a successful SQL injection attack in
a Scenario 2 situation.
I'll fix everything up eventually, but I've got a Pen Test
coming up soon, and a lot of raw code to review.
Thanksquote:
Originally posted by:
Dan Bracuk
What others can do is more relevent than what we think. When
in doubt, test.
very true, although my final solution went more like, "When
in doubt, manually add about 600 cfqueryparams in 406 cfquery
tags". -
SQL Query with Distinct and Count is wrong.
Hello,
i have another problem with a query.
Here the Data:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
CREATE TABLE TABLE_1
( "ORDER_NR" VARCHAR2 (12)
, "PRIORITY" VARCHAR2 (2)
, "WO_STATUS" VARCHAR2 (1)
, "STATUS_DATE" DATE
, "ART_NR" VARCHAR2 (9)
, "DESCRIPTION" VARCHAR2 (255)
, "PRICE" VARCHAR2 (10)
CREATE TABLE TABLE_2
( "ART_NR" VARCHAR(9)
, "MODELL" VARCHAR2(10)
, "MANUFACT" VARCHAR2(20)
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300612', '12', 'U', TO_DATE('05-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'), '005231987', '1ST ANNUAL SERVICE', '5000.2546');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '05', 'U', TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '5269.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '1ST BIENNIAL SERVICE', '1234.4468');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '4366.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300762', '12', 'U', TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'), '018743356', '3RD ANNUAL SERVICE', '4462.8632');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND ANNUAL SERVICE', '8762.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '05', 'U', TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '1ST BIENNIAL SERVICE', '3425.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND BIENNIAL SERVICE', '6678.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300612', '12', 'U', TO_DATE('06-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'), '005231987', '1ST ANNUAL SERVICE', '5000.2546');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '05', 'U', TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '5269.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '1ST BIENNIAL SERVICE', '1234.4468');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '4366.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300762', '12', 'U', TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'), '018743356', '3RD ANNUAL SERVICE', '4462.8632');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND ANNUAL SERVICE', '8762.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '05', 'U', TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '1ST BIENNIAL SERVICE', '3425.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND BIENNIAL SERVICE', '6678.6643');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT6');
COMMIT;And my query:
SELECT T1.ART_NR
, T2.MODELL
, SUM(ROUND(T1.PRICE, 2)) AS TOTAL_PRICE
, COUNT(*) AS QTY
, TO_CHAR(T1.STATUS_DATE, 'MON-RR') AS MONTH
FROM TABLE_1 T1, TABLE_2 T2
WHERE T1.WO_STATUS = 'U'
AND T1.ART_NR = T2.ART_NR
AND TO_CHAR(T1.STATUS_DATE, 'MON-RR') = 'FEB-13'
GROUP BY T2.MODELL
, T1.ART_NR
, TO_CHAR(T1.STATUS_DATE, 'MON-RR')And the result:
ART_NR MODELL TOTAL_PRICE QTY MONTH
018743356 VACCUM 559916.16 96 FEB-13
005667821 LASER 173936.48 48 FEB-13
005231987 X-RAY1 120006 24 FEB-13My problem now is, the OTY field ist wrong it should count how often the equipment was in service in FEB-13 and group it by "MODELL" the MANUFACT field is not interesting for me, but this ist my problem, one Modell can have multible Manufacter and so i got a wrong count for my QTY.
The next step i need is to group the result also by Service type (annual or biennial), like this:
ART_NR MODELL TOTAL_PRICE QTY MONTH SERVICE_TYPE
018743356 VACCUM 1234.56 4 FEB-13 ANNUAL
018743356 VACCUM 4423.48 10 FEB-13 BIENNIAL
005667821 LASER 4783.11 2 FEB-13 ANNUAL
005667821 LASER 1123.77 22 FEB-13 BIENNIAL
005231987 X-RAY1 8966.12 6 FEB-13 ANNUAL
005231987 X-RAY1 7826.44 12 FEB-13 BIENNIALThis values are only out of my head, not the table, only to show what i need.
Thanks for your help.
Greets ReinhardHi,
Here's one way:
WITH got_groups AS
SELECT art_nr
, TRUNC (status_date, 'MONTH') AS month
, CASE
WHEN UPPER (description) LIKE '%ANNUAL%'
THEN 'ANNUAL'
WHEN UPPER (description) LIKE '%BIENNIAL%'
THEN 'BIENNIAL'
END AS service_type
, TO_NUMBER (price) AS price
FROM table_1
WHERE status_date >= DATE '2013-02-01'
AND status_date < DATE '2013-03-01'
, table_2_summary AS
SELECT DISTINCT art_nr, modell
FROM table_2
SELECT g.art_nr
, s.modell
, ROUND ( SUM (g.price)
, 2
) AS total_price
, COUNT (*) AS qty
, g.month
, service_type
FROM got_groups g
JOIN table_2_summary s ON s.art_nr = g.art_nr
GROUP BY g.art_nr
, s.modell
, g.month
, g.service_type
;The reason why your aggregates were originally too high is that you have a many-to-many relationship between the tables. The tables are related only by art_nr, but art_nr is not unique in either table. Look at art_nr '005231987', example. There ate 2 rows in table_1 with that art_nr, and 6 rows in table_2 with the same art_nr. If we join on art_nr, then both of the rows in table_1 will match each of the 6 rows in table_2, so the COUNT will be 2 * 6 = 12, and in the SUM, each of the numbers from table_1 will get added 6 times.
Why is table_2 designed the way it is? Cn there be multiple modells for the same art_nr? If so, what would you want for output? If there can only be 1 modell for each art_nr, then a better design would be to have a table that just had one row per art_nr, and included the modell column, and another table to show which manufacturers produce each art_nr. In this problem, you wouldn't need the manufacturers table, and the other table already has unique art_nrs, so you wouldn't need anything like the sub-query table_2_summary.
Don't store price in a VARCHAR2 column. Storing NUMBERs in a VARCHAR2 column is just asking for problems. Why not use a NUMBER column instead.
You'll notice that I used ROUND (SUM ... where you use SUM ( ROUND. The results might be a little different because of rounding errors. ROUND ( SUM only has to call ROUND once per group (5 times in this example) instead of once per row (16 times in this example). The less rounding you do, the less rounding error creeps in. Also, since there are fewer function calls, it's more convenient. (Of course, you'll never notice the difference between calling ROUND 5 times or 16 times, but in a real-life exampe, the difference could be between calling it 50 times or calling it 16000 times.) If you really need to use SUM (ROUND, you can.
Maybe you are looking for
-
UNABLE TO LOCATE THE THE LABVIEW RUN-TIME ENGINE.LVBROKERAUX71
UNABLE TO LOCATE THE THE LABVIEW RUN-TIME ENGINE.LVBROKERAUX71 REQUIRES A VERSION 7.1 (OR COMPATIBLE) LABVIEW RUN-TIME ENGINE.PLEASE CONTACT THE VENDOR OF LVBROKERAUX71 TO CORRECT THIS PROBLEM Uninstalled DAQ and reinstalled. MAX still throws an err
-
Multiple iphones on 1 itunes?!
Hey everyone, first time posting on here!! just wondering i have an iphone 3GS as my personal phone but have now been given an iphone 3G as my work phone is it possible to sync both these phone with my itunes?! ive tried it but after ive synced my wo
-
Windows 7 Boot fails on Mac Pro 1,1 (long-standing issue)
i am having a long-standing problem on my first generation (1,1) mac pro where i have an installation of Windows 7 "under" boot camp. this installation involved some kind of minor mac hack that involved writing something to ISO and/or a CD Rom and th
-
I cant get the music to play properly with headphones attached
when my music is playing and the headphones are not plugged in, the music plays normally.. when they are pluhhed however, the music sounds deformed, [i cant hear the singer] but can i hear the music playing.. i tried pulling the plug and putting it b
-
Problem calling WebService from XI scenario
Hi forum, i trued to make a scenario to call a webservice from my XI scenario, i made it using the following blog : /people/bhavesh.kantilal/blog/2006/11/20/webservice-calls-from-a-user-defined-function I have configured a receiver SOAP channel and h