Fetch join with Native SQL Query?
Hello all,
I am using the J2EE 5.0 persistence api with the SUN appserver v9. As the java persistence api does not yet support spatial queries ("... where contains(polygon, point)") I have to use native SQL queries for that purpose.
Now my question is how can I "join fetch" my ManyToOne-related entities when using a native SQL query? Is this somehow possible using the SqlResultSetMapping annotation?
Never mind - the problem was to do with not specifying a class when creating the native query.
Similar Messages
-
Mapping Problem with Native SQL query
My application uses a native SQL query to locate certain entities. It looks like this:
SELECT UPLOADATTEMPTREF, STUDENTNUMBER, USERID, WORKITEMCODE, WORKITEMINSTURN, WORKITEMTITLE, MODULERUNCODE, STUDENTNAME, SUBMISSIONDEADLINE, UPLOADATTEMPTSERVERDATE, FILENAME, UPLOADCOMPLETESERVERDATE, NEWFILENAME, FILESIZE, FILEPATH, DOWNLOADSERVERDATE, MODULECODE, MODULETITLE
FROM Submission_Attempt WHERE UPLOADATTEMPTREF IN (
SELECT uploadAttemptRef FROM (" +<br /><br /> "SELECT MAX(uploadAttemptRef) AS uploadAttemptRef, UserID, workItemInstUrn, " +<br /><br /> "workItemCode FROM Submission_Attempt where workiteminsturn = ?1 " +<br /><br /> "GROUP BY UserID, workItemInstUrn, workItemCode) Table1 ) " +<br /><br /> "and uploadCompleteServerDate is not null;"<br />
My expectation was that EclipseLink would be able to handle the mapping of the results to the entity quite happily. However, I get a NonSynchronizedVector of Objects - each Object representing one field of data.
I need help with either:
Converting the above SQL into JPQL so that I (hopefully) don't have to worry about the SQL or
Understanding why this isn't working properly...
Anyone able to help?
Edited by: phunnimonkey on Nov 6, 2008 3:33 AMNever mind - the problem was to do with not specifying a class when creating the native query.
-
How do I join with native SQL?
I'm just starting to dip my toes in Toplink/Eclipselink using jDeveloper 11g. I've got a database schema that looks like this:
Organization > Site > Program / MhProgram
Every program and MhProgram has a site_id, and every site has an organization_id.
The POJO objects wizards seems to have set the relationships up correctly and I'm able to pull out Organization objects that have siteCollections and the sites have programCollections and MhProgramCollections. The part where I'm having trouble is pulling out organizations the way I'd like to.
I'm querying them with this SQL:
select o.*
from organization o,
site s,
program p
where o.organization_id = s.organization_id
and s.site_id = p.site_id
and s.site_number = 1
and p.program_name = "Test Name"
The problem seems to be that Toplink isn't actually recognizing that I want to do these joins. Its grabbing an organization and then doing SQL to separately get each site, then each program. During this process SQL like s.site_number = 1 is ignored. This leaves me with siteCollections and programCollections that are just raw unfiltered rows. I've tried the same with JPQL and I'm having no luck there either.
Am I missing something with the Native SQL support?
Edited by: user519677 on May 5, 2009 5:32 AMThe code is below. Its just a test client until I can get it working. When I put the word FETCH beside the INNER JOIN in the JPQL I get the following exception:
Exception Description: Syntax error parsing the query [select o from Organization o INNER JOIN FETCH o.siteCollection s where s.siteNumber = 1 ], line 1, column 63: syntax error at [s].
Internal Exception: MismatchedTokenException(66!=-1)
Code:
Project project = XMLProjectReader.read("META-INF/tlMap.xml", Thread.currentThread().getContextClassLoader());
DatabaseSession session = project.createDatabaseSession();
session.shouldLogMessages();
session.login();
session.setLogLevel(org.eclipse.persistence.logging.SessionLog.FINE);
ReadAllQuery query = new ReadAllQuery(Organization.class);
String EJBQuery = "select o from Organization o " +
"INNER JOIN o.siteCollection s " +
"where s.siteNumber = 1 ";
query.setEJBQLString(EJBQuery);
Collection<Organization> results = (Collection<Organization>) session.executeQuery(query);
Edited by: user519677 on May 5, 2009 6:31 AM -
Performance for join 9 custom table with native SQL ?
Hi Expert,
I need your opinion regarding performance to join 9 tables with native sql. Recently i have to tunning some customize extraction cost report. This report extract about 10 million cost of material everyday.
The current program actually, try to populate the condition data and insert into customize table and join all the table to get data using native sql.
SELECT /*+ ordered use_hash(mst,pg,rg,ps,rs,dpg,drg,dps,drs) */
mst.werks, ....................................
FROM
sapsr3.zab_info mst,
sapsr3.zab_pc pg,
sapsr3.zab_rc rg,
sapsr3.zab_pc ps,
sapsr3.zab_rc rs,
sapsr3.zab_g_pc dpg,
sapsr3.zab_g_rc drg,
sapsr3.zab_s_pc dps,
sapsr3.zab_s_rc drs
WHERE mst.zseq_no = :p_rep_run_id
AND mst.werks = :p_werks
AND mst.mandt = rg.mandt(+)
AND mst.ekorg = rg.ekorg(+)
AND mst.lifnr = rg.lifnr(+)
AND mst.matnr = rg.matnr(+)
............................................... unitl all table (9 tables)
AND ps.mandt = dps.mandt(+)
AND ps.knumh = dps.knumh(+)
AND ps.zseq_no = dps.zseq_no(+)
AND COALESCE (dps.kbetr, drs.kbetr, dpg.kbetr, drg.kbetr) <> 0
It seems the query ask for database to using hashed table. would that be it will burden the database ? and impacted to others sap process ?
Please advise
Thank You and Best Regardsyou can only argue coming from measurements and that is not the case.
Coming from the code, I see only that you do not understand it at all, so better leave it as it is. It is not a hash table, but a hash join on these table. -
Query SAP Database with Native Sql.
Hi,
I would like to query the table MARA with native sql and return all headings and data
Select * from MARA where MATNR = '00000000151515'
<i>I need this to be able to TEST my Sql statements.</i>
In SqlServer you have the Query Analyser where I can do just this, but is there some nice in SAP Tool for this as well ?
[Unfortanely I can't connect to SAP_U01 database from QA...]
//MartinHi Martin,
maybe you give ST05 a try: last button gives the possibility to enter a SQL-statement directly - and for explanation it has to be executed (somehow).
Regards,
Christian -
Performance of native sql query detoriates
Dear Experts,
The performance of my native SQL query is bad. On the database the query takes less than 5 seconds to process. From my abap program I get a session timeout dump after 10 minutes. What might be the possible reason.
Warm Regards,
AbdullahI am not a DBA, but this is a wild guess.
I have a native SQL query. It was running fine all morning(transported it to production today). By afternoon the report was not giving any output.
I went to the MS SQL query analyzer and executed the query, it returned the results in less than 5 seconds. The same query when I was executing from SAP using native SQL took more than 10 minutes and gave a dump(time exceeded).
My database guy asked me to execute the following on the database. Dbcc dbreindex('tablename')
The report is running fine since then. I am still not satisfied if this is the reason the performance is back on track, but yeah the report is running fine again. There seems to be some problem with the indexes.
I am using standard classes provided by SAP to execute my query and after execution the resultset reference object is being closed, I am closing the connection.
the code is as below.
PERFORM:
connect USING con_name con_ref,
select_into_table USING con_ref,
disconnect USING con_ref.
* FORM connect
* Connects to the database specified by the logical connection name
* P_CON_NAME which is expected to be specified in table DBCON. In case
* of success the form returns in P_CON_REF a reference to a connection
* object of class CL_SQL_CONNECTION.
* --> P_CON_NAME logical connection name
* <-- P_CON_REF reference to a CL_SQL_CONNECTION object
FORM connect USING p_con_name TYPE dbcon-con_name
p_con_ref TYPE REF TO cl_sql_connection
RAISING cx_sql_exception.
* if CON_NAME is not initial then try to open the connection, otherwise
* create a connection object representing the default connection.
IF p_con_name IS INITIAL.
CREATE OBJECT p_con_ref.
ELSE.
p_con_ref = cl_sql_connection=>get_connection( p_con_name ).
ENDIF.
ENDFORM. " connect
* FORM select_into_table
* Selects some rows from the test table and fetches the result rows
* into an internal table whose row structure corresponds to the
* queries select list columns.
FORM select_into_table
USING p_con_ref TYPE REF TO cl_sql_connection
RAISING cx_sql_exception.
DATA:
l_stmt TYPE string,
l_stmt_ref TYPE REF TO cl_sql_statement,
l_dref TYPE REF TO data,
l_res_ref TYPE REF TO cl_sql_result_set,
*Data related query
l_itab TYPE TABLE OF t_pricing_report,
l_row_cnt TYPE i.
* create the query string
CONCATENATE
'select A.SEQ,A.CONDTABLE,A.CONDNAME,A.VKORG,A.VTWEG,A.MATKL,A.MATNR,B.MTEXT,A.VKGRP,A.SGRPNAME,'
'A.VKBUR,A.SOFFNAME,A.ZSALES,A.SCNTNAME,A.KUNNR,A.SCSTNAME,A.PRBATCH,A.INCO1,'
'A.INCO2,A.DATAB,A.DATBI,A.KBETR,A.KONWA,A.KOSRT,B.MTART,B.GROES,B.VOLUM,B.EXTWG,B.WRKST,'
'A.MXWRT,A.GKWRT,'
'B.PATTERN,B.RIM,B.SERIES,B.SPDINDEX,B.LDINDX,B.MGROUP,B.APPLN,B.SDWALL,B.MGRPTXT'
'FROM Z_PRICELIST A,Z_MATERIALVIEW B'
'WHERE A.MANDT = ? AND'
'B.MANDT = A.MANDT AND'
'A.MATNR = B.MATNR AND'
'A.KSCHL = ? AND'
'A.CONDTABLE LIKE ? AND'
'A.VKORG LIKE ? AND'
'A.VTWEG LIKE ? AND'
'A.MATKL >= ? AND A.MATKL <= ? AND'
'A.MATNR >= ? AND A.MATNR <= ? AND'
'A.INCO1 LIKE ? AND'
'A.INCO2 LIKE ? AND'
'A.ZSALES >= ? AND A.ZSALES <= ? AND'
'A.KUNNR >= ? AND A.KUNNR <= ? AND'
'A.PRBATCH >= ? AND A.PRBATCH <= ? AND'
'A.VKBUR >= ? AND A.VKBUR <= ? AND'
'A.VKGRP >= ? AND A.VKGRP <= ? AND'
'B.WRKST >= ? AND B.WRKST <= ? AND'
'B.MTART >= ? AND B.MTART <= ? AND'
'? BETWEEN A.DATAB AND A.DATBI AND'
'B.GROES LIKE ? AND'
'B.LDINDX LIKE ? AND'
'B.SPDINDEX LIKE ? AND'
'B.RIM LIKE ? AND'
'B.SERIES LIKE ? AND'
'B.PATTERN LIKE ? AND'
'B.MGROUP LIKE ?'
'order by A.MATNR'
INTO l_stmt SEPARATED BY space. "#EC NOTEXT
* create a statement object
l_stmt_ref = p_con_ref->create_statement( ).
* bind input variables
GET REFERENCE OF l_col1 INTO l_dref.
l_stmt_ref->set_param( l_dref ).
*binding other references here
GET REFERENCE OF l_col33 INTO l_dref.
l_stmt_ref->set_param( l_dref ).
* set the input values and execute the query
l_col1 = sy-mandt.
*..Assigning values here
l_col33 = p_mgroup.
* PERFORM trace_2 USING 'EXECUTE_QUERY' l_stmt l_col1 l_col2.
l_res_ref = l_stmt_ref->execute_query( l_stmt ).
* set output table
GET REFERENCE OF l_itab INTO l_dref.
l_res_ref->set_param_table( l_dref ).
* get the complete result set
l_row_cnt = l_res_ref->next_package( ).
* display the contents of the output table
* PERFORM trace_next_package USING l_itab.
* PERFORM trace_result USING l_row_cnt 'rows fetched'.
pricing_report[] = l_itab[].
free l_itab.
* don't forget to close the result set object in order to free
* resources on the database
l_res_ref->close( ).
ENDFORM. "select_into_table
* FORM disconnect
* Disconnect from the given connection. In case of the default
* connection this can be omitted.
FORM disconnect
USING p_con_ref TYPE REF TO cl_sql_connection
RAISING cx_sql_exception.
DATA: l_con_name TYPE dbcon-con_name.
l_con_name = p_con_ref->get_con_name( ).
CHECK l_con_name <> cl_sql_connection=>c_default_connection.
* PERFORM trace_0 USING 'CLOSE CONNECTION' l_con_name.
p_con_ref->close( ).
* PERFORM trace_result USING l_con_name 'closed'.
ENDFORM. "disconnect
* FORM handle_sql_exception
* Write appropriate error messages when a SQL exception has occured
* --> P_SQLERR_REF reference to a CX_SQL_EXCEPTION object
FORM handle_sql_exception
USING p_sqlerr_ref TYPE REF TO cx_sql_exception.
FORMAT COLOR COL_NEGATIVE.
IF p_sqlerr_ref->db_error = 'X'.
WRITE: / 'SQL error occured:', p_sqlerr_ref->sql_code,
/ p_sqlerr_ref->sql_message. "#EC NOTEXT
ELSE.
WRITE:
/ 'Error from DBI (details in dev-trace):',
p_sqlerr_ref->internal_error. "#EC NOTEXT
ENDIF.
ENDFORM. "handle_sql_exception -
Hi All,
We have a native SQL query accessing Oracle database(given below).
Can anyone please let me know what this query is about and how can we fine tune the query?
SELECT O.OBJECT_NAME ,
H.SID,
HS.MACHINE,
HS.PROCESS,
W.SID,
WS.MACHINE,
WS.PROCESS,
H.CTIME,
W.CTIME,
WS.ROW_WAIT_OBJ#,
WS.ROW_WAIT_FILE#,
WS.ROW_WAIT_BLOCK#,
WS.ROW_WAIT_ROW#,
HP.SPID,
WP.SPID
FROM V$LOCK H, V$LOCK W, V$LOCK I, V$LOCK I2, ALL_OBJECTS O,
V$SESSION HS, V$SESSION WS, V$PROCESS HP, V$PROCESS WP
WHERE H.ID1 = W.ID1
AND H.SID <> W.SID
AND H.TYPE IN ('TX','DL')
AND H.REQUEST = 0
AND H.SID = I.SID
AND I.TYPE = 'TM'
AND I.ID1 = O.OBJECT_ID
AND I.ID1 = I2.ID1
AND W.SID = I2.SID
AND I2.TYPE = 'TM'
AND H.SID = HS.SID
AND W.SID = WS.SID
AND HS.PADDR = HP.ADDR
AND WS.PADDR = WP.ADDR
INTO :EXCL_LOCK_WAITERS-OBJ_NAME ,
:EXCL_LOCK_WAITERS-HOLDER_SID ,
:EXCL_LOCK_WAITERS-H_HOSTNAME ,
:EXCL_LOCK_WAITERS-HOLDER_PID ,
:HOLDER_PID ,
:EXCL_LOCK_WAITERS-WAITER_SID ,
:EXCL_LOCK_WAITERS-W_HOSTNAME ,
:EXCL_LOCK_WAITERS-WAITER_PID ,
:WAITER_PID ,
:EXCL_LOCK_WAITERS-HELD_SINCE ,
:EXCL_LOCK_WAITERS-WAITSSINCE,
:ROW_WAIT_OBJ,
:ROW_WAIT_FILE,
:ROW_WAIT_BLOCK,
:ROW_WAIT_ROW,
:H_PROCESS,
:W_PROCESS
ENDEXEC
Thanks in advance.
Neethu MohanHi Neethu,
It gives you an overwiew of blocking Oracle sessions.
1. In general, the SQL checks Oracle sessions (SID's) that were requirering a DML lock ('TM') and now holding row locks (TX) to prevent destructive interference of simultaneous conflicting DML or DDL operations. DML statements automatically acquire both table-level locks and row-level locks ('TX') => holders
It joins these with the sessions that are waiting of releasing the lock by the holders => waiters.
2. it retrieves the detail information wich Oracle process , the object (table) , it's row , block and file
are affected by the locks.
3. Normally, the locks are only hold for a short period of time. If you have blocking sessions it may be of a log running task (i.e. mass data update of a table) ; but it could also be a application bug due to improper handling of concurrent updates of the same object.
4. Tuning
V$tables are expensive to query: Why?
v$ tables are generally Oracle memory structures.
v$ tables are not read consistent.
v$ tables require latches to access -- cannot modify and read memory at the same
time.
heavy access to v$ tables like this may cause some serious heavy duty contention.
Especially if you self join V$lock several times.
So the best would be to save the contents of V$LOCK in some table:
Create table mylocks as select * from v$lock;
Use that table for self-joining and joins to the other tables.
You can also CTAS the other v$ tables to bypass the performance bottleneck while retrieving
v$ directly.
You can empty or drop the created tables any time for new data.
Because you want to investigate only lock hold for a longert time to copy the v$ memory structures into
physical tables is not a disadvantage. You certainly will wait longer on finishing your query
instead of copy them into the tables.
Hope this helped
yk -
Executing Native SQL query for oracle
Hi,
I want to run following native sql query but it is giving me error ora:933,
DATA: BEGIN OF WA,
TSP_NAME(255) TYPE C,
PER_USAGE(10) TYPE C,
END OF WA.
EXEC SQL PERFORMING loop_output.
select t.tablespace_name,'(' || TO_CHAR(ROUND(100*(NVL(b.bytes,0)/NVL(a
.bytes,0)))) || '%)' "TSUsed%" from dba_tablespaces t,
( select tablespace_name, sum(bytes)/1024/1024 bytes
from dba_data_files group by tablespace_name) a,
( select e.tablespace_name, sum(e.bytes)/1024/1024 bytes
from dba_extents e group by e.tablespace_name ) b,
( select f.tablespace_name, sum(f.bytes)/1024/1024 bytes
from dba_free_space f group by f.tablespace_name ) c
where t.tablespace_name = a.tablespace_name(+) and
t.tablespace_name = b.tablespace_name(+) and
t.tablespace_name = c.tablespace_name(+) into :wa.
ENDEXEC.
Please provide me the soln
Regards,
Bharat MistryORA-00933: SQL command not properly ended.
Try:
EXEC SQL PERFORMING loop_output.
select
into :wa
ENDEXEC.
(No "." at the end). If that doesn't work, try ending it with a ";"
Rob -
Help with an SQL Query on the Logger
We are running UCCE 8.5(3) and need help with an SQL query. When I run the below I would also like to see skill group information(name preferably)? Any help would be greatly appreciated!
select * from dbo.t_Termination_Call_Detail where DateTime between '10-11-2012 00:00:00:00' and
'10-11-2012 23:59:59:59'David, thanks for replying. Unfortunitly I don't know enough about SQL to put that into a query and have it return data. Would you be able to give an example on what the query would look like?
-
SQL JOIN with BPM sql component
Hello friends.
How to use SQL JOIN with BPM sql component?
The tables objects are created but the joined tables belong to different sql components .
I tried something like that, but a error "table doesn't exist" occours.
Ex:
for each element in
SELECT imuImovelCd
FROM IMOVEIS_URBANOS,
Integracao.FGLP.IMOVEIS_PRE_EDITAIS
WHERE IMOVEIS_URBANOS.imuImovelCd = Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipeImuCd
AND Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipePedNr = 1
AND Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipePedAa = 2008
do
extend this.imoveis using cdImovel = element.imuimovelcd,
nrImovel = call(DEC_ENDERECO, codimovel : element.imuimovelcd, tipoimovel : 1)
end
Edited by: user9008295 on 26/01/2010 05:19ok, ok you are right.
When I try use SQL Statement to make a JOIN with 2 tables on different sql objects, BPM returns "table dosn't exists".
So.... I change my code. I dont know if this is the best way to do, but... i hope u, or everyone, can help me to do a best work.
This code works fine.
for each element in
SELECT ipeImuCd
FROM Integracao.FGLP.IMOVEIS_PRE_EDITAIS
WHERE Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipePedNr = 1
AND Integracao.FGLP.IMOVEIS_PRE_EDITAIS.ipePedAa = 2008
do
for each element2 in
SELECT imuImovelDv
FROM IMOVEIS_URBANOS
WHERE imuImovelCd = element.ipeImuCd
do
extend this.imoveis using cdDvImovel = String(element2.imuImovelDv),
cdImovel = Decimal(element.ipeImuCd),
endereco = call(DEC_ENDERECO, codimovel : element.ipeImuCd, tipoimovel : 1)
end
end
Thx a lot!!! -
Flash chart with dynamic sql query does not display
Hi,
In my schema SIVOA I have a lot of tables declared like this :
CREATE TABLE "SIVOA"."EVV_xxxx"
( "CLEF_VAR" NUMBER(4,0),
"DATE1" DATE,
"VALEUR" NUMBER(16,8) Only the last part of the name changes "xxxx". For example E009, E019, etc....
I am making a chart page with report and want the user to select a name of a table and I will display using dynamic sql query, the table report and chart.
P184_ENAME is a select list returning the last part of the name of the table, fro example 'E009', 'E019', etc.
P8_CLEF_VAR is an item containing a value. This value is a key retrieved like this :SELECT CLEF_VAR
FROM SIVOA.SITE_ECHELLE
WHERE SITE = :P184_ENAMEI built a classic report using a sql dynamic function :DECLARE
x VARCHAR2 (4000);
BEGIN
x := 'SELECT NULL, DATE1, VALEUR FROM SIVOA.EVV_'
|| UPPER(:p184_ename)
|| ' WHERE CLEF_VAR = :p8_clef_var' ;
RETURN (x);
END;:p8_clef_var is an itme containing the value '4544'.
This works perfectly fine !
When I use this sql fucytion into a flash chart it does not work. I get this message "No data found".
I do not understand why a the report get a result and not the chart !
But if i hard-code the number of the CLEF_VAR instead of fetching it from :p8_clef_var I get a nice chart ! Go figure !DECLARE
x VARCHAR2 (4000);
BEGIN
x := 'SELECT NULL, DATE1, VALEUR FROM SIVOA.EVV_'
|| UPPER(:p184_ename)
|| ' WHERE CLEF_VAR = 4544 ' ;
RETURN (x);
I cannot stay with the key (CLEF_VAR) hard-coded unformtunately !
My question is how to get the chart displaying properly ??
Thank you for your kind answers.
ChristianAlex,
Using your request, with the classic report I get results (data), but I get the same message with the Flash chart : "No data found" ! I don't know how to investigate this. i tried many things but nothing works.
Christian
PS I tried this :
DECLARE
X VARCHAR2 (4000);
BEGIN
x := 'SELECT NULL, DATE1, ROUND(VALEUR,2) FROM SIVOA.EVV_'
|| UPPER (:p184_ename) ||
' WHERE CLEF_VAR = '
|| :p8_clef_var ||
' AND DATE1 BETWEEN TO_DATE ('''
||:P8_DATE_DEBUT||''', ''DD/MM/YYYY HH24:MI'') AND TO_DATE ('''
||:P8_DATE_FIN||''', ''DD/MM/YYYY HH24:MI'')'
RETURN (X);
END; But it does not work either. I could find that the SLQ syntax generated is good becaus I put it into an item which display the return done by the pls/sql.
What is sttange also with the classic report is that if I do click on next or previous to see another rows, I get the message "No data found". If I try to export the report I get an excel file with "No data fouid".
Does anybody already tried my "need" here ? i find strange thant I should not be the firs one trying to get a report an tables which name would be "dynamic".
Tahnk you.
Edited by: Christian from France on Feb 13, 2009 3:05 AM -
I have 3 hierarchical tables. [Parent] ->[Child1]->[Child2]
I have [Xref] table which stores the documents associated with these three tables. In the [Xref] table, the column “TypeID” defines to which table the document is associated with.
Below is the table structure with some sample data.
Question: Given parented I want to get all the documents associated with parent as well its children. My sql query uses Union and its working fine. But Is there any other simple way to re-write this query?
(Note that this is just an example, the actual hierarchy is pretty long so my SQL is getting little messy and I want simplify it.)
TYPES
TypeID TypeName
1 Parent
2 Child1
3 Child2
TABLE - PARENT
ParentID
1
2
3
TABLE - CHILD1
Child1ID ParentID
1 1
2 1
3 2
TABLE - CHILD2
Child2ID Child1ID
1 1
2 1
3 2
4 2
XREF
DocumentID TypeID LocatorID
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 2 3
7 3 1
8 3 2
9 3 3
10 3 4
SELECT DocumentID FROM XREF X
JOIN Parent P ON P.ParentID = x.LocatorID AND TypeID = 1 -- Parent
WHERE P.ParentID = @ParentID
UNION
SELECT DocumentID FROM XREF X
JOIN Child1 C1 ON C1.Child1ID = x.LocatorID AND TypeID = 2 -- Child1
JOIN Parent P ON P.ParnetID = C1.ParentID
WHERE P.ParentID = @ParentID
UNION
SELECT DocumentID FROM XREF X
JOIN Child2 C2 ON C2.Child1ID = x.LocatorID AND TypeID = 3 -- Child2
JOIN Child1 C1 ON C1.Child1ID = c2.Child1ID
JOIN Parent P ON P.ParnetID = C1.ParentID
WHERE P.ParentID = @ParentIDCan you child span multiple levels? If yes, best way would be to use CTE
see
http://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Cartesian join in the SQL query
Hi,
I have a problem when joining two tables that cannot join directly. As I read (please correct me if I'm wrong), two dims have to join by one fact in order to extract information from them. This way, I created logical source tables with SQL query that join both dims. So, if for example Dim A and Dim B cannot join directly, I created a "mapping table" which is a select that joins these 2 tables in the proper way and the fields are the row_wids from these tables. This way, I created the following model diagram for this relationship:
DimActivity -< FactMapping >- DimPNR
DimActivity -< FactActivity >- DimMapping
DimPNR -< FactPNR >- DimMapping
Now, I can extract information from both dims and their metrics, except in one case; If I extract info from ("Segment Designer") "Dim-Activity", "Dim-PNR", "Fact-Activity" and "Fact-PNR", I get a query that first calculates the metric from Activity, then calculates the metric from PNR, and when it joins both queries, I get cardinality because it doesn't join through the "mapping tables". The whole query is:
WITH
SAWITH0 AS (select sum(T690608."QTY") as c1,
T690608."ASSET_NUM" as c2
from "W_ASSET_D" T690608 /* Dim_W_ASSET_D */
group by T690608."ASSET_NUM"),
SAWITH1 AS (select sum(T682428."COST") as c1,
T682428."STATUS_WID" as c2
from "W_ACTIVITY_F" T682428 /* Dim_W_ACTIVITY_F */
group by T682428."STATUS_WID")
select distinct SAWITH0.c2 as c1,SAWITH1.c2 as c2,SAWITH1.c1 as c3,SAWITH0.c1 as c4
from
SAWITH0,SAWITH1
Why there is no condition joining SAWITH0 and SAWITH1? Is there a way to force this to be an inner join? I'm looking forward to your answer, since this problem is urgent within this project. Thank you in advanceOk.
I assume that you have for one activity several asset PNR and for one asset several activity.
The factPNR is on this way a real bridge table. It's a way to be able to design a many-to-many relationship.
Have a look here for more detail on how to build a many-to-many relationship :
http://gerardnico.com/wiki/dw/data_quality/relationships#many-to-many
Therefore I assume that you want this design :
DimActivity -< FactActivity >- < FactPNR >- DimPNR and you will have :
DimActivity -< FactActivity >- < BridgeTable >- DimPNR How to build your bridge table ?
In the physical layer, :
* create a new table BridgeActivityPNR, open it and select "statement"
* enter your sql statement
SELECT DISTINCT A.ROW_WID ACTIVIDAD_WID, B.ROW_WID ASSET_WID
FROM W_ACTIVITY_F A,
W_ASSET_D B,
W_SRVREQ_D C,
X_S_CMPT_MTRC_F D,
X_S_ASSET_FEA_D E
WHERE A.X_SRA_SR_ID=C.INTEGRATION_ID AND
C.X_VLG_FLIGHT_ID=D.X_ROW_ID AND
D.X_ROW_ID=E.X_CM_ID AND
E.X_ASSET_ID=B.X_ROW_ID* add two columns in the column tab : ACTIVIDAD_WID and ASSET_WID
* create the physical join with the table FactActivity and DimPNR
* drag and drop in the business model your table BridgeActivityPNR
* in the BMM, create the complex join like this :
DimActivity -< FactActivity >- < BridgeTable >- DimPNR * open your logical bridge table and check the bridge table option.
And you are done if I didn't forget anything.
A complete example here :
http://gerardnico.com/wiki/dat/obiee/obiee_bridge_table -
Problem with native SQL cursor in generic data source
Hi, All!
I am implementing generic data source based on FM.
Because of complicated SQL I canu2019t use Open SQL and RSAX_BIW_GET_DATA_SIMPLE-example u201Cas isu201D.
So, I have to use Native SQL. But Iu2019ve got a problem with a cursor. When I test my data source in RSA3, everything is Ok. But, if I start appropriate info-package, I get error u201CABAP/4 processor: DBIF_DSQL2_INVALID_CURSORu201D. It happens after selecting of 1st data package in line u201CFETCH NEXT S1 INTOu2026u201D. It seems to me that when system performs the second call of my FM the opened cursor has already been disappeared.
Did anyone do things like this and what is incorrect?
Is it real to make generic data source based on FM with using Native SQL open, fetch, closeu2026Hi Jason,
I don't think this SQL is very valuable It is just an aggregation with some custom rules. This aggregation is performing on info-provider which consists of two info-cubes. Here we have about 2 billion records in info-provider and about 30 million records in custom db-table Z_TMP (certainly, it has indexes). I have to do this operation on 21 info-providers like this and I have to do this 20 times for each info-provider (with different values of host-variable p_GROUP)
SELECT T.T1, SUM( T.T2 ), SUM( T.T3 ), SUM( T.T4 )
FROM (
SELECT F."KEY_EVENT06088" AS T1,
F."/BIC/EV_COST" + F."/BIC/EV_A_COST" AS T2,
DECODE( D.SID_EVENTTYPE, 23147, 0,
23148, 0,
23151, 0,
23153, 0,
23157, 0,
23159, 0,
24896734, 0,
695032768, 0,
695029006, 0,
695029007, 0,
695036746, 0, F."/BIC/EV_COST") +
DECODE( D.SID_EVENTTYPE, 23147, 0,
23148, 0,
23151, 0,
23153, 0,
23157, 0,
23159, 0,
24896734, 0,
695032768, 0,
695029006, 0,
695029007, 0,
695036746, 0, F."/BIC/EV_A_COST") AS T3,
DECODE( D.SID_EVENTTYPE, 23147, F."/BIC/EV_DURAT",
23148, F."/BIC/EV_DURAT",
23151, F."/BIC/EV_DURAT",
23153, F."/BIC/EV_DURAT",
23157, F."/BIC/EV_DURAT",
23159, F."/BIC/EV_DURAT",
24896734, F."/BIC/EV_DURAT",
695032768, F."/BIC/EV_DURAT",
695029006, F."/BIC/EV_DURAT",
695029007, F."/BIC/EV_DURAT",
695036746, F."/BIC/EV_DURAT", 0) AS T4
FROM "/BIC/VEVENT0608F" F,
Z_TMP G,
"/BIC/DEVENT06085" D
WHERE F."KEY_EVENT06088" = G.ID
AND F."KEY_EVENT06085" = D.DIMID
AND G.GROUP_NO = :p_GROUP
AND ( F."/BIC/EV_COST" < 0 OR F."/BIC/EV_A_COST" < 0 )
AND D.SID_EVENTTYPE <> 695030676 AND D.SID_EVENTTYPE <> 695030678
UNION
SELECT F."KEY_EVNA06088" AS T1,
F."/BIC/EV_COST" + F."/BIC/EV_A_COST" AS T2,
DECODE( D.SID_EVENTTYPE, 23147, 0,
23148, 0,
23151, 0,
23153, 0,
23157, 0,
23159, 0,
24896734, 0,
695032768, 0,
695029006, 0,
695029007, 0,
695036746, 0, F."/BIC/EV_COST") +
DECODE( D.SID_EVENTTYPE, 23147, 0,
23148, 0,
23151, 0,
23153, 0,
23157, 0,
23159, 0,
24896734, 0,
695032768, 0,
695029006, 0,
695029007, 0,
695036746, 0, F."/BIC/EV_A_COST") AS T3,
DECODE( D.SID_EVENTTYPE, 23147, F."/BIC/EV_DURAT",
23148, F."/BIC/EV_DURAT",
23151, F."/BIC/EV_DURAT",
23153, F."/BIC/EV_DURAT",
23157, F."/BIC/EV_DURAT",
23159, F."/BIC/EV_DURAT",
24896734, F."/BIC/EV_DURAT",
695032768, F."/BIC/EV_DURAT",
695029006, F."/BIC/EV_DURAT",
695029007, F."/BIC/EV_DURAT",
695036746, F."/BIC/EV_DURAT", 0) AS T4
FROM "/BIC/VEVNA0608F" F,
Z_TMP G,
"/BIC/DEVNA06085" D
WHERE F."KEY_EVNA06088" = G.ID
AND F."KEY_EVNA06085" = D.DIMID
AND G.GROUP_NO = :p_GROUP
AND ( F."/BIC/EV_COST" < 0 OR F."/BIC/EV_A_COST" < 0 )
AND D.SID_EVENTTYPE <> 695030676 AND D.SID_EVENTTYPE <> 695030678
) T
GROUP BY T.T1 -
Please help me with this SQL query
I am practicing SQL queries and have come across one involving fetching data from 3 different tables.
The three tables are as below
<pre>
Country
location_id country
loc1 Spain
loc2 England
loc3 Spain
loc4 USA
loc5 Italy
loc6 USA
loc7 USA
</pre>
<pre>
User
user_id location_id
u1 loc1
u2 loc1
u3 loc2
u4 loc2
u5 loc1
u6 loc3
</pre>
<pre>
Post
post_id user_id
p1 u1
p2 u1
p3 u2
p4 u3
p5 u1
p6 u2
</pre>
I am trying to write an SQL query - for each country of users, display the average number of posts
I understand the logic behind this that we first need to group together all the locations and then the users belonging to one country and then find the average of their posts.
But, i'm having a difficulty in putting this in SQL form. Could someone please help me with this query.
Thanks.select
country.country,
count(*) Totalpostspercountry,
count(distinct post.user_id) Totaldistincuserspercountry,
count(*)/count(distinct post.user_id) Avgpostsperuserbycountry
from
country, muser, post
where country.location_id = muser.location_id
and muser.user_id = post.user_id
group by country.country
The output is like this for your sample data - hope this is what you were looking for :)
COUNTRY,TOTALPOSTSPERCOUNTRY,TOTALDISTINCUSERSPERCOUNTRY,AVGPOSTSPERUSERBYCOUNTRY
England,1,1,1,
Spain,5,2,2.5,
Maybe you are looking for
-
HP Officejet pro X451dw connected to LAN with persistant error code 0xc6fd0313. Display tells me that there is a problem with the printer or ink system - please turn off and back on again. This does not resolve the issue. Help!
-
Defining a Background | Adobe Muse Feature Tour | Adobe TV
Fill your background with repeating images or any image you choose. Muse will handle optimization when you publish. http://adobe.ly/I5cS02
-
Set location in runtime..
Hi usually i used to save file like this String retreive = textarea.getText(); RandomAccessFile logfile = new RandomAccessFile("c:\\saved.txt","rw"); logfile.writeBytes(retreive); JOptionPane.showMessageDialog(null,"Save
-
I have a SB Li've 5. card but cannot get surround sound in version 5536 of Vista, any ideas.
-
Hi Expert please suggest SQL Logic to Add this same account for different time period for same Year CATEGORY RPTCURRENCY YEAR ACCOUNTFBENTITYCOSTCENTER FBTIME SIGNEDDATA MAYF GBP 2010 ACCPYCALC CEGB11SED20950