Retriveial of data based on inner joins
I have Five tables (Subject,English,Hindi,Maths,Science,Social)
where Subject is the Primary table and rest all lookup table For Subject
My select Statement need to display all chapter names Based on the ID's in subject table
SELECT English.ChapterName AS English, Hindi.ChapterName AS Hindi, Maths.ChapterName AS Maths, Social.ChapterName AS Social,
Science.ChapterName AS Science
FROM Subjects INNER JOIN
English ON Subjects.English = English.ChapterNo INNER JOIN
Hindi ON Subjects.Hindi = Hindi.ChapterNo INNER JOIN
Maths ON Subjects.Maths = Maths.ChapterNo INNER JOIN
Science ON Subjects.Science = Science.ChapterNo INNER JOIN
Social ON Subjects.Social = Social.ChapterNo
WHERE (Subjects.SubjectID = 1)
If it's SubjectID 1 we can get the result set as complete data is populated What about SubjectID 3and 4 as some value's are null
How can I retrive the output for them
Sample Data
Create table English (ChapterNo int,ChapterName varchar(50))
Insert into English values (1,'English1')
Insert into English values (2,'English2')
Insert into English values (3,'English3')
Insert into English values (4,'English4')
Insert into English values (5,'English5')
Insert into English values (6,'English6')
Create table Maths (ChapterNo int,ChapterName varchar(50))
Insert into Maths values (1,'Maths1')
Insert into Maths values (2,'Maths2')
Insert into Maths values (3,'Maths3')
Insert into Maths values (4,'Maths4')
Insert into Maths values (5,'Maths5')
Insert into Maths values (6,'Maths6')
Create table Hindi (ChapterNo int,ChapterName varchar(50))
Insert into Hindi values (1,'Hindi1')
Insert into Hindi values (2,'Hindi2')
Insert into Hindi values (3,'Hindi3')
Insert into Hindi values (4,'Hindi4')
Insert into Hindi values (5,'Hindi5')
Insert into Hindi values (6,'Hindi6')
Create table Science (ChapterNo int,ChapterName varchar(50))
Insert into Science values (1,'Science1')
Insert into Science values (2,'Science2')
Insert into Science values (3,'Science3')
Insert into Science values (4,'Science4')
Insert into Science values (5,'Science5')
Insert into Science values (6,'Science6')
Create table Social (ChapterNo int,ChapterName varchar(50))
Insert into Social values (1,'Social1')
Insert into Social values (2,'Social2')
Insert into Social values (3,'Social3')
Insert into Social values (4,'Social4')
Insert into Social values (5,'Social5')
Insert into Social values (6,'Social6')
Create Table Subjects (SubjectID int,English int,Maths int ,Hindi int ,Science int,Social int )
Insert into Subjects (SubjectID,English,Maths,Hindi,Science,Social) values (1,1,1,1,1,1)
Insert into Subjects (SubjectID,English,Maths,Hindi,Science,Social) values (2,1,2,3,2,4)
Insert into Subjects (SubjectID,English,Maths) values (3,1,2)
Insert into Subjects (SubjectID,English,Social) values (2,1,4)
Insert into Subjects (SubjectID,English,Maths,Social) values (2,1,3,4)
Insert into Subjects (SubjectID,English,Maths,Hindi,Science) values (2,1,2,3,2)
I have Tried Using Inner joins other than this i donot find any other way of doing this .If I insert Default values in all the tables it works and my Lead wont agree.
There Should Be Some way I hope which i am not able to figure it out .
I hope someone must have faced this problem and they can definitely work it out
Similar Messages
-
Facing problem in selecting data based on the join s tatement ppls suggest
hi
cosider a sceneio as below
there are six tables table1
table2
table3 table4
table5 table6
join conditons between tables
table1-lclic (primary key) = table2-lclic
table1-lgreg = table3-lgreg (PK for table 3)
table2-pobj = table4-pobj
i have used join statment to join table 1 table 2table3
i want to select data from table5
table5-ccngn and table6-text
now condion for validation is that
table5-field1 is selected if table4-ctsex = table3-ctsty and tehre is no link between table 5 and table 3 o nly link is through table 4
table4-ctsnum=table5-ctsnum (primary keys)
can anyone suggest how to format the select statement
regards
AroraHi Nishant,
Using Table Joins for multiple tables would severely hamper the performance of the SAP system.
Instead use individual select statements for each database table, and later reconcile all the internal tables.
<b>Reward points, if helpful.</b>
Regards,
Atin -
How to control outer group data based on inner group data
Hi ,
Please can anyyone help me on this issue.
I have one invoice header record and for that invoice there are 15invoice lines record.
1)my requirement is i want to print the 10 invoice records in first page and remaining records,in next page.--this i had achieved*(byusing solution posted inthe forum)*
i have the layout like this
image:!C:\Documents and Settings\madhu.rn\Desktop\layout.jpg!
main group data table
i had inserted another table for inner group data.
again main group data in main table.
2)But here i don't want print header info again in second page.
3)i am not getting the line numbers in inner group in ascending order ,i am getting in descending order. how to get them in decending order
4) if lines record are going to second page i don't want to print subtotal,tax,total (these are main group data)in first page, instead of this
in place of
subtotal-- want to print Continued......
Tax- null
Total:page 1 of 2. like that i want to print in first page.
i want them to print in second page.
5)the bottom portion also not to print on second page.(after innergroup data,there is some main group data)
i have one doubt by using inner group data whether we can control outer group data.
if any of my requirement's are not possible to meet ,please provide me the information.
This urgent for me,have to submit it.
Edited by: user644268 on Feb 8, 2010 11:10 AMHi,
Please help me in this issue. Its an urgent requirement.
Thanks in Advance.. -
How to find Inner join or (Left)outer join for Infoset
Dear Experts,
We have one Infoset which is based on the Master data and DSO. It is linked 0BPARTNER field From the Master Data and SOLD TO PARTY field from the DSO.
Here Could you please suggest me how can we able to find that whether this Infoset is based on Inner Join or (Left) outer join.
Thanks and Regards,
Suresh.HI Suresh,
If the infoset is based on left outer join , you see the respective table shaded in a dirrerent colour and also displays
that it is a left outer join in the connection
refer the below link for the details on left outer join , you can make a join as left outer from the context menu of the
object required
http://help.sap.com/erp2005_ehp_04/helpdata/EN/21/af0942b9dc9c39e10000000a155106/frameset.htm
Regards,
Sathya -
HI all,
How to access data from two internal table using join condition ?
suppose i have tow internal table itab and jtab and i want to access data by using inner join on this tow table.
please tell .
thanx..hi,
You can use PROVIDE ENDPROVIDE statements in ABAP to achive this.
Check the below documenttaion.
PROVIDE
Syntax
PROVIDE FIELDS {*|{comp1 comp2 ...}}
FROM itab1 INTO wa1 VALID flag1
BOUNDS intliml1 AND intlimu1
[WHERE log_exp1]
FIELDS {*|{comp1 comp2 ...}}
FROM itab2 INTO wa2 VALID flag2
BOUNDS intliml2 AND intlimu2
[WHERE log_exp2]
BETWEEN extliml AND extlimu
[INCLUDING GAPS].
ENDPROVIDE.
Effect
The statements PROVIDE and ENDPROVIDE define a loop through a statement block. In this loop, any number of internal tables itab1 itab2 ... are processed together. A single table can appear several times. For every table itab you must specify a FIELDS clause. After FIELDS you must specify the character * for all components or a list comp1 comp2 ... for specific components of the relevant table. The names of the components comp1 comp2 ... can only be specified directly.
To be able to process internal tables using PROVIDE, all tables itab1 itab2 ... must be fully typed index tables and contain two special columns that have the same data type (d, i, n, or t) for all relevant tables. For every table you must specify the names intliml1 intliml2 ... and intlimu1 intlimu2 ... of these columns using the addition BOUNDS.
The columns intliml1 intliml2 ... and intlimu1 intlimu2 ... in every row of the relevant internal tables must contain values that can be interpreted as limits of closed intervals. Within a table, the intervals specified in these columns must not overlap and must be sorted in ascending order. The intervals therefore make up a unique key for every row.
For every table you must specify a work area wa1 wa2 ... compatible with the row type and a variable flag1 flag2 ..., for which a character-type data type with length 1 is expected. In the PROVIDE loop, the components specified after FIELDS are filled with values in the relevant work areas wa1 wa2 ... for every specified internal table. The variables flag1 flag2 ... are also filled. A work area wa1 wa2 ... or a variable flag1 flag2 ... cannot be specified more than once.
With the BETWEEN addition you must specify an interval extliml, extlimu. It must be possible to convert the data objects extliml and extlimu into the data types of the respective columns intliml1 intliml2 ... and intlimu1 intlimu2 ... of the individual tables.
The interval limits intliml1 intliml2 ... and intlimu1 intlim2 for every row of all relevant internal tables itab1 itab2 ... that are within the closed interval made up by extliml and extlimu divide the latter into new intervals and every interval limit closes one interval in the original direction. If, within a relevant table, a lower interval limit follows an upper interval limit with no space or gap between them and the components of the corresponding rows specified after FIELDS have the same content, the two intervals are combined and the corresponding interval limits intliml1 intliml2 ... and intlimu1 intlimu2 ... are ignored for the new intervals.
For every interval that is created in such a way and overlaps with at least one of the intervals of a table involved, the PROVIDE loop is passed once. The components of every work area wa1 wa2 ... specified after FIELDS and the variables flag1 flag2 ... are filled with values as follows:
The components intliml1 intliml2 ... and intlimu1 intlimu2 ... of every work area wa1 wa2 ... are filled with the interval limits of the current interval.
If the current interval overlaps with one of the intervals of an involved table, the remaining components of the corresponding work area are assigned the contents of the relevant components of this table row and the variable flag1 flag2 ... is set to the value "X". Otherwise, the work area components and the variables flag1 flag2 ... are set to their Initial value.
Except for intliml1 intliml2 ... and intlimu1 intlimu2 ..., the components not specified after FIELDS are always set to their initial value. The components intliml1 intliml2 ... and intlimu1 intlimu2 ... are always assigned.
The ABAP runtime environment checks for every table involved, whether the condition of sorted and non-overlapping intervals is met within the interval made up by extliml and extlimu and, if necessary, triggers an exception that can be handled.
If the INCLUDING GAPS addition is specified, the system passes the PROVIDE loop for every interval, that is also when the current interval does not overlap with at least one of the intervals of an involved table. In the latter case, the variable flag is of initial value for every relevant table.
You can use the WHERE addition to specify a condition for every table itab1 itab2 ... involved. After WHERE, you can specify any logical expression log_exp1 log_exp2 ... ; the first operand of every comparison must be a component of the internal table. As such, all logical expressions except for IS ASSIGNED, IS REQUESTED, and IS SUPPLIED are possible. You can only specify components that are in the list after FIELDS. Here it is not possible to specify a component using character-type data objects in brackets. The table entries for which the condition is not met are ignored by the PROVIDE loop. You can leave the PROVIDE loop following the instructions in the section Leaving loops.
System fields
The system fields sy-subrc and sy-tabix are set to the value 0 before every loop pass and at ENDPROVIDE. Only if the loop is not passed once, is sy-subrc set to 4 at ENDPROVIDE.
Notes
The relevant internal tables should not be modified in the PROVIDE loop.
The WHERE condition can be used to remove overlaps between the tables involved or to ensure the sorting of the intervals.
In two tables itab1 and itab2, the respective columns col1 and col2 are interval limits of type i. The filling of the internal tables results in the following intervals (rows two and three):
|01|02|03|04|05|06|07|08|09|10|11|12|13|14|
| Itab1 Int1 | |Itab1 Int2 | |
| | Itab2 Int1 | |
| | ... BETWEEN ... |
| | i1 | i2 | i3 | i4 |i5| |
The interval specified in the BETWEEN addition to the PROVIDE statement is shown in the fourth row. It serves as a basis for the five intervals in the fifth row represented by i1 to i5. These can be processed in the PROVIDE loop.
Because each of the five intervals overlaps with one of the intervals from rows two and three, the PROVIDE loop is passed five times.
Only the component col3 of wa1 is filled in the first pass, only the component col3 of wa2 in the third pass, and the components col3 of both work areas in the second and fourth passes. The fields valid1 and valid2 are set accordingly.
DATA: BEGIN OF wa1,
col1 TYPE i,
col2 TYPE i,
col3 TYPE string,
END OF wa1.
DATA: BEGIN OF wa2,
col1 TYPE i,
col2 TYPE i,
col3 TYPE string,
END OF wa2.
DATA: itab1 LIKE STANDARD TABLE OF wa1,
itab2 LIKE STANDARD TABLE OF wa2.
DATA: flag1(1) TYPE c,
flag2(1) TYPE c.
wa1-col1 = 1.
wa1-col2 = 6.
wa1-col3 = 'Itab1 Int1'.
APPEND wa1 TO itab1.
wa1-col1 = 9.
wa1-col2 = 12.
wa1-col3 = 'Itab1 Int2'.
APPEND wa1 TO itab1.
wa2-col1 = 4.
wa2-col2 = 11.
wa2-col3 = 'Itab2 Int1'.
PROVIDE FIELDS col3 FROM itab1 INTO wa1
VALID flag1
BOUNDS col1 AND col2
FIELDS col3 FROM itab2 INTO wa2
VALID flag2
BOUNDS col1 AND col2
BETWEEN 2 AND 14.
WRITE: / wa1-col1, wa1-col2, wa1-col3, flag1.
WRITE: / wa2-col1, wa2-col2, wa2-col3, flag2.
SKIP.
ENDPROVIDE.
The list output is as follows:
2 3 Itab1 Int1 X
2 3
4 6 Itab1 Int1 X
4 6 Itab2 Int1 X
7 8
7 8 Itab2 Int1 X
9 11 Itab1 Int2 X
9 11 Itab2 Int1 X
12 12 Itab1 Int2 X
12 12
Exceptions
Catchable Exceptions
CX_SY_PROVIDE_INTERVAL_OVERLAP
Cause: In one of the involved tables there are overlapping intervals within extlim1 and extlim2.
Runtime Error: UNCAUGHT_EXCEPTION
CX_SY_PROVIDE_TABLE_NOT_SORTED
Cause: One of the involved tables is not sorted in ascending order by the intervals within extlim1 and extlim2.
Runtime Error: UNCAUGHT_EXCEPTION
Edited by: Velangini Showry Maria Kumar Bandanadham on Apr 28, 2008 1:36 PM -
Data is not fetching in inner join
Hi Experts,
I developed a select query using inner joins, all the fields data is gettting appended, but one field DISPO data is not getting appeneded. please check the innerjoin and suggest me ur soluitons.
MODULE GET_DATA OUTPUT.
select arbpl
sptag
aufnr
plnum
posnr
plnfl
werks from s022
into table it_s022
where arbpl in s_arbpl
and werks in s_werks
and sptag in s_sptag
and matnr in s_matnr.
if sy-subrc eq 0.
select a~aufnr
a~posnr
a~kdauf
a~pgmng
a~plnum
a~strmp
b~plnty
b~gamng
b~igmng
b~iasmg
b~rmnga
b~gstrp
b~rsnum
b~plnbez
b~dispo
c~maktx
b~plnnr
b~plnty
b~zaehl
d~vornr
d~ltxa1
b~aufpl
b~aplzt
e~astnr
into corresponding fields of table it_afpo from afko as b
inner join afpo as a
on a~aufnr = b~aufnr
inner join makt as c
on b~plnbez = c~matnr
inner join plpo as d
on b~plnnr = d~plnnr
and b~plnty = d~plnty
and b~zaehl = d~zaehl
inner join aufk as e
on b~aufnr = e~aufnr
inner join marc as f
on bplnty = fmatnr
for all entries in it_s022
where b~aufnr = it_s022-aufnr.
and e~erdat = it_s022-sptag
and a~posnr = it_s022-posnr
and a~plnum = it_s022-plnum . .
if sy-subrc eq 0.
it_afpo1[] = it_afpo[].
sort it_afpo1 by aufpl." aplzt."""
delete ADJACENT DUPLICATES FROM it_afpo1 COMPARING aufpl." aplzt ."""
select aufpl
aplzl
fsavd
fsavz
ssedd
ssedz
mgvrg
FROM afvv INTO TABLE It_afvv
FOR ALL ENTRIES IN IT_afpo1
WHERE aufpl = IT_afpo1-aufpl.
and aplzl = it_afpo1-aplzt.
endif.
loop at it_afpo into wa_afpo.
DATA : G_SLNO(8) TYPE C.
G_SLNO = G_SLNO + 1.
wa_afpo-slno = g_slno.
move-corresponding wa_afpo to wa_final.
move-corresponding wa_afko to wa_final.
read table it_afvv into wa_afvv with key
aufpl = wa_afpo-aufpl binary search."aplzl = wa_afpo-aplzt binary search."""
*read table it_afko into wa_afko with key aufnr = wa_final-aufnr.
IF SY-SUBRC EQ 0.
move-corresponding wa_afvv to wa_final.
bal_qty = wa_final-gamng - wa_final-igmng.
move : wa_afpo-slno to wa_final-slno,
wa_afpo-aufnr to wa_final-aufnr,
wa_afpo-posnr to wa_final-posnr,
wa_afpo-kdauf to wa_final-kdauf, " Sales order Number
wa_afpo-pgmng to wa_final-pgmng, " Order item qty
wa_afpo-plnum to wa_final-plnum, " Planned Order Qty
wa_afpo-strmp to wa_final-strmp, " Planned Order Date
wa_afpo-gstrp to wa_final-gstrp, " Basic Finish date
wa_afpo-rsnum to wa_final-rsnum, " Number of Reservation
wa_afpo-plnbez to wa_final-plnbez, " Material Number
wa_afpo-maktx to wa_final-maktx,
wa_afpo-plnnr to wa_final-plnnr,
wa_afpo-plnty to wa_final-plnty,
wa_afpo-zaehl to wa_final-zaehl,
wa_afpo-vornr to wa_final-vornr,
wa_afpo-ltxa1 to wa_final-ltxa1,
wa_afpo-aufpl to wa_final-aufpl,
wa_afvv-fsavd to wa_final-fsavd,
wa_afvv-fsavz to wa_final-fsavz,
wa_afvv-ssedd to wa_final-ssedd,
wa_afvv-ssedz to wa_final-ssedz,
wa_afvv-mgvrg to wa_final-mgvrg,
wa_afko-igmng to wa_final-igmng,
wa_afko-iasmg to wa_final-iasmg,
wa_afko-rmnga to wa_final-rmnga,
wa_afko-dispo to wa_final-dispo,
wa_afko-bal_qty to wa_final-bal_qty,
wa_aufk-astnr to wa_final-astnr,
wa_afpo-text to wa_final-text.
*bal_qty = wa_final-gamng - wa_final-igmng.
*bal_qty = wa_afko-bal_qty.
endif.
append wa_final to it_final.
clear:wa_final ,wa_afpo,wa_afvv,wa_aufk,wa_afko.
endloop.
endif.
ENDMODULE. " GET_DATA OUTPUT
*& Module DISPLAY_DATA OUTPUT
text
MODULE DISPLAY_DATA OUTPUT.
IF REF_CONTAINER IS INITIAL.
PERFORM FIELD_CAT.
CREATE OBJECT REF_CONTAINER
EXPORTING
PARENT =
CONTAINER_NAME = 'CUSTOM_CONTROL'
STYLE =
LIFETIME = lifetime_default
REPID =
DYNNR =
NO_AUTODEF_PROGID_DYNNR =
EXCEPTIONS
CNTL_ERROR = 1
CNTL_SYSTEM_ERROR = 2
CREATE_ERROR = 3
LIFETIME_ERROR = 4
LIFETIME_DYNPRO_DYNPRO_LINK = 5
others = 6
IF SY-SUBRC <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
L_LAYO-ZEBRA = 'X'.
L_LAYO-GRID_TITLE = 'JOB CARD'.
data: variant type disvariant.
CREATE OBJECT REF_ALV_GRID
EXPORTING
I_SHELLSTYLE = 0
I_LIFETIME =
I_PARENT = REF_CONTAINER
I_APPL_EVENTS = space
I_PARENTDBG =
I_APPLOGPARENT =
I_GRAPHICSPARENT =
I_NAME =
I_FCAT_COMPLETE = SPACE
EXCEPTIONS
ERROR_CNTL_CREATE = 1
ERROR_CNTL_INIT = 2
ERROR_CNTL_LINK = 3
ERROR_DP_CREATE = 4
others = 5
IF SY-SUBRC <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
l_variant-report = sy-cprog.
*data: l_prnt type lvc_s_prnt.
*l_prnt-print = 'X'.
SORT T_FCAT.
call method ref_alv_grid->set_ready_for_input
exporting
i_ready_for_input = 1.
create object event_receiver.
set handler event_receiver->handle_top_of_page for ref_alv_grid.
CALL METHOD REF_ALV_GRID->SET_TABLE_FOR_FIRST_DISPLAY
EXPORTING
I_BUFFER_ACTIVE =
I_BYPASSING_BUFFER =
I_CONSISTENCY_CHECK =
I_STRUCTURE_NAME =
is_variant = variant "l_variant
i_save = 'X'
I_DEFAULT = 'X'
IS_LAYOUT = L_LAYO
IS_PRINT =
IT_SPECIAL_GROUPS =
IT_TOOLBAR_EXCLUDING =
IT_HYPERLINK =
IT_ALV_GRAPHICS =
IT_EXCEPT_QINFO =
IR_SALV_ADAPTER =
CHANGING
IT_OUTTAB = IT_final[]
IT_FIELDCATALOG = T_FCAT
IT_SORT =
IT_FILTER =
EXCEPTIONS
INVALID_PARAMETER_COMBINATION = 1
PROGRAM_ERROR = 2
TOO_MANY_LINES = 3
others = 4
IF SY-SUBRC <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
create object g_event_receiver.
set handler g_event_receiver->handle_user_command for ref_alv_grid.
set handler g_event_receiver->handle_toolbar for ref_alv_grid.
§ 4.Call method 'set_toolbar_interactive' to raise event TOOLBAR.
call method ref_alv_grid->set_toolbar_interactive.
call method cl_gui_control=>set_focus exporting control = ref_alv_grid.
ENDIF.
ENDMODULE. " DISPLAY_DATA OUTPUT
*& Module STATUS_0100 OUTPUT
text
MODULE STATUS_0100 OUTPUT.
SET PF-STATUS 'MAIN001'.
SET TITLEBAR 'xxx'.
Regards,
Bharath KumarI agree with Shiva Kumar - most likely there is no such field in it_afpo. A few more suggestions though:
1) Do not post large pieces of code here - if you have a question about a particular SELECT statement, post only that statement and relevant data definitions. No one is going to read your whole program anyway - we have work to do too.
2) Your JOIN is way too big and would be difficult to analyze if anything goes wrong. You might want to start with smaller SELECTs and, when you're sure everything is working correctly, then combine them into one. Also huge JOINT is not necessarily more efficient.
3) You don't have to use aliases "AS a... AS b", etc. Instead, just use the table name, e.g. AFKO... AFPO... .It is much easier to read this way. The aliases are needed only if you're joining the same table more than once. Also they're not limited to one letter either. -
Inner join in ABAP and exporting the data
Hi,
I want to use inner join in ABAP for retrieving data from 2 tables and export that data.How will i do it?Hi,
Refer following code
*--Select query to pick the data from table VBRK
VBRP and VBPA using inner join
SELECT a~vbeln "Billing document
a~fkdat "Billing date
a~fktyp "Billing category
a~fkart "Billing type
a~vtweg "Distribution channel
a~knumv "Number of doc condition
b~posnr "Billing item
b~matnr "Material Number
b~werks "Plant
b~vgbel "Referance
b~netwr "Net value of billing item
b~wavwr "Cost in document currency
c~kunnr "Partner function
FROM vbrk AS a
INNER JOIN vbrp AS b
ON avbeln EQ bvbeln
INNER JOIN vbpa AS c
ON bvbeln EQ cvbeln
AND bposnr EQ cposnr
INTO CORRESPONDING FIELDS OF TABLE it_vbrp
WHERE fkdat IN s_erdat
AND parvw EQ 'ZS'.
IF sy-subrc EQ 0.
*--Sort table by
SORT it_vbrp BY vgbel1.
ENDIF.
Regards,
Prashant -
Inner Join Subquery data display
I have a query that uses a sub query on a INNER JOIN
SELECT SUM(A.qtyord), A.Item, A.Description, A.Class, B.Forecast,
CASE
WHEN B.Forcast = 0
THEN A.Item
ELSE
CASE
WHEN (SUM(A.ORDQ)/B.Forcase) > 0.20
THEN A.Item
ELSE ''
END
END AS SKU
FROM tableA A
INNER JOIN ((SELECT Item, ( SUM(BBAL) + SUM(RECV) + SUM(ADJU) - SUM(ALOC)) as onhand FROM tableD GROUP BY Item)) D ON A.Item = D.Item
INNER JOIN tableB B ON A.Item=B.Item
INNER JOIN tableC C ON B.Item=C.Item
GROUP BY A.Item, A.Description, A.Class, B.Forecast
ORDER BY A.Class DESC
How do I get the data from the sub query to display.Hello,
Please check whether the following statement meet your requirment:
;With cte as
SELECT Item, ( SUM(BBAL) + SUM(RECV) + SUM(ADJU) - SUM(ALOC)) as onhand
FROM tableD GROUP BY Item)
SELECT SUM(A.qtyord), A.Item, A.Description, A.Class, B.Forecast, cte.onhand,
CASE
WHEN B.Forcast = 0
THEN A.Item
ELSE
CASE
WHEN (SUM(A.ORDQ)/B.Forcase) > 0.20
THEN A.Item
ELSE ''
END
END AS SKU
FROM tableA A
INNER JOIN cte ON A.Item = cte.Item
INNER JOIN tableB B ON A.Item=B.Item
INNER JOIN tableC C ON B.Item=C.Item
GROUP BY A.Item, A.Description, A.Class, B.Forecast
ORDER BY A.Class DESC
Regards,
Fanny Liu
If you have any feedback on our support, please click here.
Fanny Liu
TechNet Community Support -
Hi all,
Here is what I am trying to do. I have 2 tables A and B. Both have a fiscal year and a school ID column. I want to return all data from table B where all school IDs match but fiscal year from A is not in B. I wrote 2 queries below but this took
2 minutes each to process through 30,000 records in table B. Need to optmize this query.
1) select 1 from table A inner join table B
on A.SchoolID=B.SchoolID where A.Year not in (select distinct Year from table B)
2) select distinct Year from Table A where School ID in (select distinct School ID from table B
and Year not in (select distinct Year from table B)Faraz81,
query execution time will depend not only on your data volume and structure but also on your system resources.
You should post your execution plans and DDL to generate data structures so we can take a better look, but one think you could try right away is to store the results of the subquery in a table variable and use it instead.
You'll also benefit from the creation of:
1. An index for the B.SchoolID column.
2. Statistics for the Year column in table B.
You can also try to change the physical algorithm used to join A to B by using query hints (HASH, MERGE, LOOP) and see how they perform. For example:
select 1 from table A inner HASH join table B
on A.SchoolID=B.SchoolID where A.Year not in (select distinct Year from table B)
As the query optimizer generally chooses the best plan, this might not be a good idea though, but then again, without further information its going to be hard to help you. -
How to produce the effect of a date range inner join without actually doing one
I have a T-SQL inner date range join that has done the job, but now that I am starting to learn about query optimization (as in just starting), I'm scratching my head on how to make it better. I see the non-equi join as being the issue because the optimizer
scans through the entire table. As you will see from the DDL code pasted below, there are no possible equi-joins. The enrollment history table has about 6000 rows so far, whereas the calendar table has only 10 so far, but is subject to change, which
is why I have it as a table join.
Another way to describe this is in the necessary outcome, which you see in the "Is_FAY" column in the Select statement. For each row in the Enrollment History table, I use the Case statement to determine whether the pair of Entry and Exit dates
are within the Calendar date ranges (and if so, which row the match is found). There are no nulls in either table by design.
At first, I thought of adding a non-clustered index, but the credible resources and blogs are mixed. Some sources say to use them, others say not to use them, and the remainder are on the fence. That and the
fact that I drop and recreate the table every 24 hours (there are many updates to the Black Box) makes me very leery about having indices other than the primary key.
I have pasted DDL language below with sample data. Change the "Use Learning_Curve" statement to whatever database you want to use -- the rest will run as written.
Now that I've given you some background and what I hope to accomplish, I hope that someone has encountered this issue before and can suggest an avenue of further inquiry, because I am out of usable research sources and ideas.
Thank you
USE Learning_Curve;
GO
IF OBJECT_ID('dbo.Enrollment_History', 'U') IS NOT NULL
DROP TABLE dbo.Enrollment_History;
CREATE TABLE dbo.Enrollment_History
(ID INT NOT NULL identity(1, 1) PRIMARY KEY,
Campus_ID INT NOT NULL,
Student_ID INT NOT NULL,
Entry_Date DATE NOT NULL,
Exit_Date DATE NOT NULL);
INSERT INTO dbo.Enrollment_History
VALUES (1, 103934, '2014-08-11', '2015-01-10'),
(1, 102912, '2014-09-10', '2015-05-10'),
(1, 199234, '2014-08-07', '2015-05-01');
IF OBJECT_ID('dbo.Calendar_FAY_Dates', 'U') IS NOT NULL
DROP TABLE dbo.Calendar_FAY_Dates;
CREATE TABLE dbo.Calendar_FAY_Dates
(ID INT NOT NULL identity(1, 1) PRIMARY KEY,
FY VARCHAR(4) NOT NULL,
Start_B DATE NOT NULL,
Start_E DATE NOT NULL,
End_B DATE NOT NULL,
End_E DATE NOT NULL);
INSERT INTO dbo.Calendar_FAY_Dates
VALUES ('FY14', '2013-08-05', '2013-08-29', '2014-04-30', '2014-05-15'),
('FY15', '2014-08-07', '2014-08-28', '2015-04-30', '2015-05-15');
SELECT eh.ID,
eh.Campus_ID,
eh.Student_ID,
eh.Entry_Date,
eh.Exit_Date,
cfd.FY,
case
when eh.Entry_Date >= cfd.Start_B
and eh.Entry_Date <= cfd.Start_E
and eh.Exit_Date >=cfd.End_B
and eh.Exit_Date <= cfd.End_E
then 1 else 0 end as Is_FAY
FROM dbo.Enrollment_History eh
inner join dbo.Calendar_FAY_Dates cfd
on eh.Entry_Date >= cfd.Start_B
and eh.Exit_Date <= cfd.End_EThis definitely a case where an indexes on the two tables will speed things up significantly.
It's also one of those strange cases where you can't really rely on the numbers you see in the execution plan. To really get an idea the impact to need to actually time the query...
For example. Running your final query with out any additional indexes took ~4,000 microseconds...
Adding the following index, dropped that time down to ~3,000 microseconds...
CREATE NONCLUSTERED INDEX ix_Enrollment_History_EntryDates ON dbo.Enrollment_History (
Entry_Date,
Exit_Date)
INCLUDE (
ID,
Campus_ID,
Student_ID)
WITH (DATA_COMPRESSION = PAGE)
Adding the following index (and keeping the 1st) dropped it again, down to ~2,000 microseconds
CREATE NONCLUSTERED INDEX ix_CalendarFAYDates_Detes ON dbo.Calendar_FAY_Dates (
Start_B,
End_E)
INCLUDE (
Start_E,
End_B,
ID,
FY)
WITH (DATA_COMPRESSION = PAGE)
Keep in mind that 5 rows of data doesn't even begin to provide an accurate representation of read execution times against actual production data (the smallest changes in background processes on my computer caused the time to vary pretty drastically between
executions).
Anyway, the following is a quick & dirty way to test execution times when you're query tuning or checking the impact of different indexes on a query.
DECLARE @b DATETIME2(7) = SYSDATETIME()
SELECT eh.ID,
eh.Campus_ID,
eh.Student_ID,
eh.Entry_Date,
eh.Exit_Date,
cfd.FY,
case
when eh.Entry_Date >= cfd.Start_B
and eh.Entry_Date <= cfd.Start_E
and eh.Exit_Date >=cfd.End_B
and eh.Exit_Date <= cfd.End_E
then 1 else 0 end as Is_FAY
FROM dbo.Enrollment_History eh
inner join dbo.Calendar_FAY_Dates cfd
on eh.Entry_Date >= cfd.Start_B
and eh.Exit_Date <= cfd.End_E
SELECT DATEDIFF(mcs, @b, SYSDATETIME())
HTH,
Jason
Jason Long -
Hi,
I extracted data from two datasources a FI data source and 2LIS_03_BF.
I matched these two data sources through:
MBLNR-----AWREF = 0REF_DOC_NR
MJAHR-----AWGJA = 0DOC_YEAR
When the data is merged in the cube its a outer join and the data isnt matched.
HOW DO I DO AN INNER JOIN TO MATCH ALL THE DATA TOGETHER?
Cheers~it is going in the same cube... what would an ifo set do? would it merge my data? i have never used one before
Scenerio is :
Cube A has data from 2lis_03_bf
Cube B has data from 0fi_gl_4
Cube C im extracting data from A and B to merge data
Edited by: DANIEL GREEN on May 2, 2008 2:10 AM -
Edit form with an Inner Join - Can not update/delete data?!
Hi all,
I have an Edit form which shows me data from 2 tables (through an Inner Join SQL-Statement). I just realized that I can not edit data anymore, the following error msg appears:
Error in mru internal routine: ORA-20001: no data found in tabular form
Error Unable to process update.
OK
Can someone please help me?The ringed in red are from the second table, but the first table has some more data. Here is the SQL Statement I have (D1 and D2 are from the second table - Whereas the DOBJ_NR1 and the DOBJ_NR2 are both primary keys and foreign keys in table one, but the user selects the key from table two...):
SELECT
D1.DOBJ_NR DOBJ_NR1,
D1.NAMSP NAMSP1,
D1.DOBJ_NAME DOBJ_NAME1,
D2.DOBJ_NR DOBJ_NR2,
D2.NAMSP NAMSP2,
D2.DOBJ_NAME DOBJ_NAME2,
R.RS_NAME,
R.ROLE1TO2,
R.CARDMIN1TO2,
R.CARDMAX1TO2,
R.ROLE2TO1,
R.CARDMIN2TO1,
R.CARDMAX2TO1,
R.ON_DELETE,
R.ON_UPDATE,
R.O_RS_COMMENT,
R.INS_BY REL_INS_BY
FROM
DO_RELATIONSHIP R
INNER JOIN DATAOBJECT D1 ON R.DOBJ1_NR = D1.DOBJ_NR
INNER JOIN DATAOBJECT D2 ON R.DOBJ2_NR = D2.DOBJ_NR
Edited by: user12067949 on Dec 5, 2009 3:18 AM -
Inner join with data also from non having join column
I have an Dim table which has to be joined with Fact Table using inner join, but also display the Dimension value " MasterGroup " inspite of data present or not in the fact table.
My Query: .. This is an part of my stored procedure with more tables
SELECT a.SalesAmount, b.HeaderGroup ,c.CityName
FROM dbo.FactItem a
inner join dbo.[DimHeader] b
on a.sid = b.sid
left join dbo.DimCity c
on a.cityid = c.id
My DimHeader Table will have data like
MasterGroup
ChildGroup
etc...
which is an attribute.
There might not be any relevent fact data, but still i want the dimension data to display the "MasterGroup"
ShanmugaRajhello ,
usually this is not possible when the column you want to display when the matches not found from a table having a distinct values which are hard to declared static..
you can incorporate something like this if you cant change the join type ..
select distinct HeaderGroup from dbo.[DimHeader] tbl_outerleft join (SELECT a.sid,a.SalesAmount, b.HeaderGroup ,c.CityName
FROM dbo.FactItem a
inner join dbo.[DimHeader] b
on a.sid = b.sid
left join dbo.DimCity c
on a.cityid = c.id) tbl_Main on tbl_Main.sid =tbl_outer.sid
Dilip Patil.. -
Inner Join of 3 tables is correct or not?
Hi Guys ,
I have a requirement where i have to join 3 tables i dont know whether the inner Join which i wrote for 3 tables is correct or not.I am not getting any Syntax error but whether the logci below which i wrote gets all the records or not.
The Requirement is
"c. Select the BOL Number entered in the screen and query the table LIKP with the BOL number in the field LIKP-BOLNR. Gather the list of ALL delivery documents (LIKP-VBELN) that is outputted.
d. Query the list of the delivery documents obtained into the table VBFA in the field VBFA- VBELV. From the output that is displayed, select the Follow-On Document Field (VBFA-VBELN) for that item whose Subsequent Document Category (VBFA- VBTYP_N) is R and the Movement Type (VBFA- BWART) is 641. Get the Follow-On document number for each of the above Delivery Document number.
e. Query the table EKBE with the Follow On document obtained above in the field Material Document (EKBE- BELNR). Perform this activity for each of the follow on document obtained above. Get the resultant Purchase Order (EKBE-EBELN) and Item Number (EKBE-EBELP) from the query. After querying will all the Follow-On Documents, get the unique list of PO number and Item Number.
The logic which i wrote is
Begin of t_PoolSTO_out,
BOLNR type LIKP-BOLNR,
EBELN type EKBE-EBELN,
EBELP type EKBE-EBELP,
VBELN type LIKP-VBELN,
VBELNV type VBFA-VBELN,
End of t_PoolSTO_out.
Data: i_PoolSTO type Standard table of t_PoolSTO_out.
Select
a~BOLNR
c~EBELN
c~EBELP
a~VBELN
b~VBELN
from LIKP as a
Inner Join VBFA as b on aVBELN = bVBELV
Inner Join EKBE as c on bVBELN = cBELNR
into Table i_PoolSTO
Where a~BOLNR in S_LBLNE and
b~VBTYP_N = 'R' and
b~BWART = '641'.
My doubt is whether the logic works or not i Mean does i getall the rrecords based on the requirement.?
If not please tell any alternative logic?
Thanks,
Gopi Anne.Hi Gopi,
Your code is Good.
But try to avoid Inner join with more number of Tables ...because this is a performance issue..
try to use..
select (primary key fields mainly,other fields) from LIKP into itab where bolnr in p_bolnr(paramater).
next try to use for all entries option..
select (primary key fields mainly,other fields) from VBFA for all entries in itab where (give the condition)....
simillarly do for the other select ....ok this will try to reduce the performance issue....
<b><REMOVED BY MODERATOR></b>
Message was edited by:
Alvaro Tejada Galindo -
Help needed in rewriting the code using inner joins
Hi all,
I need help in rewriting this code
DATA : FLD LIKE ZTABLE-ZFLD,
FLD1 LIKE ZTABLE2-ZFLD2.
select single ZFLD from zTABLE1 into FLD
where MATNR = '123' and
werks = 'ABC'.
select single ZFLD1 from zTABLE2 into FLD1
where zFLD = FLD.
iS there way that we can write this with inner joins
ThanksHi,
help me out
TABLE 1 HAS
MATNR , WERKS , FLD1.
TABLE 2 HAS
FLD1, FLD2.
I KNOW MATNR AND WERKS BASED ON THAT I HAVE TO GET FLD2
I WANT IT BE WRITTEN WITH INNEWR JOINS
WITH FOLLOWING COD E I GET AN ERROR MESSAGE SAYING
comma without preccing colon (after select?)
data : FLD1 like zTABLE1-ZFLD1.
data : FLD2 like ZTABLE2-ZFLD2.
SELECT FZFLD1 BZFLD2
INTO ( FLD1, FLD2)
FROM ZTABLE1 AS F INNER JOIN ZTABLE2 AS B
ON FZFLD1 = BFLD2
WHERE F~MATNR = '123'
AND F~WERKS = 'ABC' .
Thanks
Maybe you are looking for
-
UE or BADI within MIGO Posting
Hi all. I need to call Z transaction within the posting action of MIGO process. I had tried to use MB_MIGO_BADI and MB_DOCUMENT_BADI but when I tried to write set up a break point it didn't stop there. Does anyone has an idea about a specific user-ex
-
How to print an email with the full name of the attachment ?
In Mail, when using "View as an Icon", the name of the attachment - if too long - does not appear in full. Any tip on how to have the full name appears (for archiving purpose) ? Thank you
-
How to remove the copyright Text
Hi, I wan to remove the copyright text(*Copyright (c) 2006, Oracle. All rights reserved.*) from the OAF page. How to do that? Any help would be highly appreciated.. Thanks...
-
Unable to sync iPad to iMac. Get message 'iPad can't be synced because not enough free space to hold items in iTunes Library'. Only major content is iTunes U stuff (lots of videos). Don't download any music or other videos to iPad. Deleted iTunesU co
-
Hello, I'm making a website about losing weight, and I feel like I need more pictures. Problem is, most pictures have copyright or are too expensive for me. Where can I find free pictures without anu copyright or watermarks? My website is www.echt-af