Join on tables
We have 3 tables
T1 T2 T3
a1 a2 c3
b1 b2 d3
c2
d2
They are joined on conditions:
T1-T2:
a1=a2
and T2-T3:
c2=c3
The requirement is we want to join the tables as:
T1-T2:
a1=a2 or b1=b2
and T2-T3:
c2=d2 or d2=d3
Can this be done?
Then, what will happen to the cases:
1. When a1, d2 is given
2. b1, c2 is given
Hi,
A. Drieux answered your first question, so I'll do the second one.
if b1 and c2 are null (only a1 and d2 given), T1 will be correctly joined to T2 through a1-a2 and T1 will also be correctly joined to T3 through d2-d3.
Same when only b1, c2 are provided ;)
Hope it helps.
Regards,
JeromeFr
Similar Messages
-
I am trying to develop a query in MS Access 2010 to join two tables using three joins, one of which is a (between) date range. The tables are contained in Access. The reason
the tables are contained in access because they are imported from different ODBC warehouses and the data is formatted for uniformity. I believe this cannot be developed using MS Visual Query Designer. I think writing a query in SQL would be suiting this project.
ABCPART links to XYZPART. ABCSERIAL links to XYZSERIAL. ABCDATE links to (between) XYZDATE1 and ZYZDATE2.
[ABCTABLE]
ABCORDER
ABCPART
ABCSERIAL
ABCDATE
[ZYXTABLE]
XYZORDER
XYZPART
XYZSERIAL
XYZDATE1
XYZDATE2Thank you for the looking at the post. The actual table names are rather ambiguous. I renamed them so it would make more sense. I will explain more and give the actual names. What I do not have is the actual data in the table. That is something I don't have
on this computer. There are no "Null" fields in either of the tables.
This table has many orders (MSORDER) that need to match one order (GLORDER) in GLORDR. This is based on MSPART joined to GLPART, MSSERIAL joined to GLSERIAL, and MSOPNDATE joined if it falls between GLSTARTDATE and GLENDDATE.
[MSORDR]
MSORDER
MSPART
MSSERIAL
MSOPNDATE
11111111
4444444
55555
2/4/2015
22222222
6666666
11111
1/6/2015
33333333
6666666
11111
3/5/2015
This table has one order for every part number and every serial number.
[GLORDR]
GLORDER
GLPART
GLSERIAL
GLSTARTDATE
GLENDDATE
ABC11111
444444
55555
1/2/2015
4/4/2015
ABC22222
666666
11111
1/5/2015
4/10/2015
AAA11111
555555
22222
3/2/2015
4/10/2015
Post Query table
GLORDER
MSORDER
GLSTARTDATE
GLENDDATE
MSOPNDATE
ABC11111
11111111
1/2/2015
4/4/2015
2/4/2015
ABC22222
22222222
1/5/2015
4/10/2015
1/6/2015
ABC22222
33333333
1/5/2015
4/10/2015
3/5/2015
This is the SQL minus the between date join.
SELECT GLORDR.GLORDER, MSORDR.MSORDER, GLORDR.GLSTARTDATE, GLORDR.GLENDDATE, MSORDR.MSOPNDATE
FROM GLORDR INNER JOIN MSORDR ON (GLORDR.GLSERIAL = MSORDR.MSSERIAL) AND (GLORDR.GLPART = MSORDR.MSPART); -
I have to join 18 tables,.. Is it best to join all 18 in a single shot or to go with
multi stages-- 9 tables in one stage and after that anotther 9 tables..
Please anyone give me a good suggestion on this with some reason...
Thanks in advanceIf you can look at your query and recognise that it is trying to collect (say) two small result sets and then join the result sets, then it is actually a good idea to express the query in that fashion to Oracle.
Take for example a query that sums last week's profits for a supermarket by department using a 9 table query in about 2 minutes. A similar query reports the previous week's profits with a marginally different query in about two minutes. You write the two queries as inline views and join them to report the percentage change in profit by department - and the query takes 4 hours because Oracle has used "complex view merging" to turn your two 9-table queries into a single 18-table query.
In this case, a workaround is to use the /*+ no_merge */ hint. In outline, something like:
select {columns}
from
select /*+ no_merge */
dept_no,
etc.
from ...
) lw,
select /*+ no_merge */
dept_no,
etc.
from ...
) pw
where
pw.dept_no = lw.dept_no
;In less obvious cases you may still be able to find that you can break up a big query into a few smaller, logical sections, and use this technique to generate and join what are, in effect, intermediate results.
An alternative to the /*+ no_merge */ hint is to use subquery factoring to the same end. There's a more complex example of the method here: http://jonathanlewis.wordpress.com/2007/07/01/internet-sql/
In either case, avoid turning your 18-table query into 18 separate pieces and sticking them back together - it may make the optimizer do some very silly things. Karen Morton mentions an example of this on her blog: http://karenmorton.blogspot.com/2008/06/dont-do-work-you-dont-have-to-do.html
Regards
Jonathan Lewis
http://jonathanlewis.wordpress.com
http://www.jlcomp.demon.co.uk
"The greatest enemy of knowledge is not ignorance,
it is the illusion of knowledge." (Stephen Hawking) -
Using a view to join two tables
Thank you in advance for any advice you can lend.
I am using this code in my MySQL db to create a view.
select
job.id as job_id,
umr_cost_calculation.plant_name,
max(umr_cost_calculation.id) as max_id
from
job,
umr_cost_calculation
where
job.id = umr_cost_calculation.job_id
group by job.id , umr_cost_calculation.plant_name
I did this so I can join two tables and pull in the most current cost data for a specific plant. The report will, at times, show the wrong (older) data. I can re-run the report, filter to just the one job and see again the wrong data. When I add the max_id to the report, it display the id and updates the report with the correct data. It appears that the view was stale and by adding the ID to the report this fixed the issue.
1) Is this the best way to make this join? I don't see how Crystal supports a subquery to make a join (this is why I used the view).
2) If I leave the max_id on the report, will this force the view to always update?Try:
Select
D1.EmpLoginID,
Count(D1.ID),
Count(D1.AlarmCode),
D1.EmpName,
D1.EmpAddress,
D2.Db2Count
FROM DB1.Data D1
LEFT JOIN (SELECT
empLoginID, Count(*) as Db2Count
FROM DB2.ALL_Database
WHERE site = 'Atlanta'
GROUP BY empLoginID
) D2
ON D1.EmpLoginID = D2.EmpLoginID
GROUP BY D1.empLoginID, D1.EmpName, D2.EmpAddress, D2.Db2Count
Order BY D1.empLoginID ASC
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
Help needed in using Pivot by joining 2 tables
Hello everyone,
I am very new to usage of Pivot that includes joining 2 tables. Below is the scenario and request your help in this regard.
Table1
ID1 Description
1 Stationary
2 Apparel
3 Home Decor
Note : ID1 is unique
Table2
ID2 ID1 Item
1 1 Book
2 1 Paper-A4
3 2 T-Shirt
4 1 Pencil
5 3 Flower Vase
Note : ID2 is unique
I am trying to get the below result set.
ID2 Stationary Apparel Home Decor
1 Book NULL NULL
2 Paper-A4 NULL NULL
3 NULL T-Shirt NULL
4 Pencil NULL NULL
5 NULL NULL Flower Vase
Please help in this regard.
Thanks in advance,
KiranJust guessing
SELECT id2,
CASE WHEN Description='Stationary'
THEN Item END [Stationary],
CASE WHEN Description='Apparel'
THEN Item END [Apparel],
CASE WHEN Description='Home
Decor' THEN Item END [ Home
Decor]
FROM t1 JOIN t2 ON t1.id1=t2.id1
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Using functions in select statement(joining 5 tables) taking long time in Oracle
Hi,
I have created a query in oracle which joins 5 tables and uses two functions(function names are 'ca_concat' and 'ca_concat_noseq').
Query takes approximately 40 secs to execute around 12000 records. If I remove the functions from query it excutes within a second..
Note : I have used the oracle SQL Developer for testing the query.
It would be appriciated if anybody helps me to improve the perfomance of the query.
Below are the querie with and without functions:
1. Query with functions:
select
imsAuditEvent12.id as ID,
imsAuditEvent12.audit_time as AUDIT_TIME,
imsAuditEvent12.admin_dn as ADMIN_DN,
imsAuditEvent12.admin_name as ADMIN_NAME,
imsAuditEvent12.event_name as EVENT_NAME,
imsAuditEvent12.event_description as EVENT_DESCRIPTION,
imsAuditEvent12.event_state as EVENT_STATE,
imsAuditEvent12.envname as ENVNAME,
imsAuditTaskSession12.task_name as TASK_NAME,
imsAuditTaskSession12.id as TASK_ID,
imsAuditTaskSession12.task_description as TASK_DESCRIPTION,
imsAuditTaskSession12.task_priority as TASK_PRIORITY,
S1.OBJECT_ID,
S1.OBJECT_NAME as OBJECT_NAME,
S1.OBJECT_TYPE as OBJECT_TYPE,
S2.ATTRIBUTE_NAME as ATTRIBUTE_NAME,
S2.ATTRIBUTE_OLDVALUES as ATTRIBUTE_OLDVALUES,
S2.ATTRIBUTE_NEWVALUES as ATTRIBUTE_NEWVALUES,
S3.OBJECT_DN as OBJECT_DN,
S3.OBJECT_TYPE as IMSOBJECT_TYPE,
S3.CONTAINER_NAME as CONTAINER_NAME,
S3.CONTAINER_DN as CONTAINER_DN,
S3.CONTAINER_TYPE as CONTAINER_TYPE
from
imsAuditEvent12 LEFT JOIN imsAuditTaskSession12 ON imsAuditTaskSession12.id=imsAuditEvent12.tasksession_id LEFT JOIN
(select parent_event_id,
ca_concat('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.object_name','imsAuditEventObject12') as OBJECT_NAME,
ca_concat('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.object_type','imsAuditEventObject12') as OBJECT_TYPE,
ca_concat_noseq('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.ID','imsAuditEventObject12') as OBJECT_ID
from
imsAuditEventObject12 group by parent_event_id) S1
ON imsAuditEvent12.id = S1.parent_event_id LEFT JOIN
(select
parent_object_id,
ca_concat('parent_object_id',parent_object_id,'attribute_name','imsauditobjectattributes12') as ATTRIBUTE_NAME,
ca_concat('parent_object_id',parent_object_id,'attribute_oldvalue','imsauditobjectattributes12') as ATTRIBUTE_OLDVALUES ,
ca_concat('parent_object_id',parent_object_id,'attribute_newvalue','imsauditobjectattributes12') as ATTRIBUTE_NEWVALUES
from
imsauditobjectattributes12 group by parent_object_id) S2
ON S1.OBJECT_ID = S2.parent_object_id LEFT JOIN
(select
parent_event_id,
ca_concat('parent_event_id',parent_event_id,'OBJECT_DN','imsauditobjectrelationship12') as OBJECT_DN,
ca_concat('parent_event_id',parent_event_id,'OBJECT_TYPE','imsauditobjectrelationship12') as OBJECT_TYPE ,
ca_concat('parent_event_id',parent_event_id,'CONTAINER_NAME','imsauditobjectrelationship12') as CONTAINER_NAME,
ca_concat('parent_event_id',parent_event_id,'CONTAINER_DN','imsauditobjectrelationship12') as CONTAINER_DN,
ca_concat('parent_event_id',parent_event_id,'CONTAINER_TYPE','imsauditobjectrelationship12') as CONTAINER_TYPE
from
imsauditobjectrelationship12 group by parent_event_id) S3
ON imsAuditEvent12.id =S3.parent_event_id where imsauditevent12.id > 0 and imsauditevent12.id <12000 order by imsauditevent12.id ASC;
2. Query without using functions:
select * from imsauditeventobject12 left join imsauditevent12 on imsauditeventobject12.id=imsauditevent12.id left join imsauditobjectattributes12 on imsauditeventobject12.id=imsauditobjectattributes12.parent_object_id left join imsaudittasksession12 on imsauditevent12.tasksession_id=imsaudittasksession12.id left join imsAuditObjectRelationship12 on imsAuditEvent12.id =imsAuditObjectRelationship12.parent_event_id where imsauditevent12.id >0 and imsauditevent12.id < 12000 order by imsauditevent12.id asc;
Thanks,
BadriHi,
Please find the below more information about the query.
DB version: Oracle 11g Enterprise Edition Release 11.2.0.1.0
Below are source of the functions:
create or replace function ca_concat( ca_key_name in varchar2,
ca_key_val in varchar2,
ca_other_col_name in varchar2,
ca_tname in varchar2 )
return varchar2
as
type rc is ref cursor;
l_str varchar2(32000);
l_sep varchar2(1);
l_val varchar2(32000);
l_count number(6);
l_cur rc;
begin
l_count :=1;
l_str := '';
open l_cur for 'select '|| ca_other_col_name ||'
from '|| ca_tname || '
where ' || ca_key_name || ' = '
using ca_key_val;
loop
fetch l_cur into l_val;
l_val := SUBSTR(l_val,0,102);
exit when (l_cur%notfound or l_count > 38);
l_str := l_str || l_sep || l_count || '.' || l_val;
l_sep := ',';
l_count := l_count + 1;
end loop;
close l_cur;
return l_str;
end;
create or replace function ca_concat_noseq( ca_key_name in varchar2,
ca_key_val in varchar2,
ca_other_col_name in varchar2,
ca_tname in varchar2 )
return varchar2
as
type rc is ref cursor;
l_str nvarchar2(32000);
l_sep varchar2(1);
l_val varchar2(32000);
l_count number(6);
l_cur rc;
begin
l_count :=1;
open l_cur for 'select '||ca_other_col_name||'
from '|| ca_tname || '
where ' || ca_key_name || ' = '
using ca_key_val;
loop
fetch l_cur into l_val;
exit when (l_cur%notfound or length(l_val)>3000 or l_count>1);
l_str := l_str || l_sep || l_val ;
l_sep := ',';
l_count := l_count + 1;
end loop;
close l_cur;
return l_str;
end;
Below are the tables structures:
DESC imsauditevent12;
Name Null Type
ID NOT NULL NUMBER
TASKSESSION_ID NOT NULL NUMBER
TASKSESSION_OID VARCHAR2(100)
PARENT_EVENT_OID VARCHAR2(100)
AUDIT_TIME NOT NULL TIMESTAMP(6)
EVENT_OID NOT NULL VARCHAR2(100)
ADMIN_DN NOT NULL VARCHAR2(512)
ADMIN_NAME VARCHAR2(255)
EVENT_NAME NOT NULL VARCHAR2(255)
EVENT_DESCRIPTION VARCHAR2(4000)
EVENT_STATE VARCHAR2(100)
ENVNAME NOT NULL VARCHAR2(100)
ENV_OID NOT NULL VARCHAR2(100)
DESC imsauditeventobject12;
Name Null Type
ID NOT NULL NUMBER
PARENT_EVENT_ID NOT NULL NUMBER
AUDIT_TIME NOT NULL TIMESTAMP(6)
OBJECT_TYPE NOT NULL VARCHAR2(100)
OBJECT_NAME VARCHAR2(255)
DESC imsauditobjectattributes12;
Name Null Type
ID NOT NULL NUMBER
PARENT_OBJECT_ID NOT NULL NUMBER
AUDIT_TIME NOT NULL TIMESTAMP(6)
DISPLAY_NAME VARCHAR2(255)
ATTRIBUTE_NAME NOT NULL VARCHAR2(255)
ATTRIBUTE_OLDVALUE VARCHAR2(4000)
ATTRIBUTE_NEWVALUE VARCHAR2(4000)
DESC imsaudittasksession12;
Name Null Type
ID NOT NULL NUMBER
PARENT_TS_OID VARCHAR2(100)
PARENT_EVENT_OID VARCHAR2(100)
AUDIT_TIME NOT NULL TIMESTAMP(6)
TASKSESSION_OID NOT NULL VARCHAR2(100)
ADMIN_DN NOT NULL VARCHAR2(512)
ADMIN_NAME VARCHAR2(255)
TASK_NAME VARCHAR2(255)
TASK_TAG NOT NULL VARCHAR2(255)
TASK_DESCRIPTION VARCHAR2(4000)
TASK_PRIORITY NUMBER
STATE NOT NULL VARCHAR2(100)
ENVNAME NOT NULL VARCHAR2(100)
ENV_OID NOT NULL VARCHAR2(100)
DESC imsAuditObjectRelationship12;
Name Null Type
ID NOT NULL NUMBER
PARENT_EVENT_ID NOT NULL NUMBER
AUDIT_TIME NOT NULL TIMESTAMP(6)
OBJECT_TYPE NOT NULL VARCHAR2(100)
OBJECT_DN NOT NULL VARCHAR2(512)
CONTAINER_TYPE NOT NULL VARCHAR2(100)
OBJECT_NAME NOT NULL VARCHAR2(255)
CONTAINER_NAME NOT NULL VARCHAR2(255)
CONTAINER_DN NOT NULL VARCHAR2(512)
OPERATION NOT NULL VARCHAR2(50)
Thanks,
Badri -
How do you join two tables from different Oracle schemas using a subquery
I am trying to join two tables from different Oracle schemas using a subquery. I can extract data from each of the tables without a problem. However, when I combine the select statements using a subquery I get the Oracle error *'ORA-00936: missing expression'*. Since each SELECT statement executes on its own without error I don't understand what is missing. The result set I am trying to get is to match up the LINE_ID from PDTABLE_12_1 in schema DD_12809 with the MAT_DESCRIPTION from table PDTABLE_201 in schema RA_12809.
The query is as follows:
sql = "SELECT [DD_12809].[PDTABLE_12_1].LINE_ID FROM [DD_12809].[PDTABLE_12_1] JOIN " _
+ "(SELECT [RA_12809].[PDTABLE_201].MAT_DESCRIPTION " _
+ "FROM [RA_12809].[PDTABLE_201]) AS FAB " _
+ "ON [DD_12809].[PDTABLE_12_1].PIPING_MATER_CLASS = FAB.PIPING_MATER_CLASS"
The format of the query is copied from a SQL programming manual.
I also tried executing the query using a straight JOIN on the two tables but got the same results. Any insight would be helpful. Thanks!
Edited by: user11338343 on Oct 19, 2009 6:55 AMI believe you are receiving the error because you are trying to JOIN on a column that doesn't exist. For example you are trying to join on FAB.PIPING_MATER_CLASS but that column does not exist in the subquery.
If you want to do a straight join without a subquery you could do the following
SELECT DD_12809.PDTABLE_12_1.LINE_ID
, FAB.MAT_DESCRIPTION
FROM DD_12809.PDTABLE_12_1
JOIN RA_12809.PDTABLE_201 AS FAB ON DD_12809.PDTABLE_12_1.PIPING_MATER_CLASS = FAB.PIPING_MATER_CLASS HTH! -
Join fact table with higher dimension level
how do i join fact tables with higher dimension levels with discoverer?
fact with detail at level C
measure X
dimension with
D->C->B->A
E->C
level
A B C
1------1------1
2------2------1
3------2------1
join between fact X and dimension level C
X=3*C because of sum(X) in discoverer and 3xC in dimension
is there a way to get correct values for X without creating a dimension like
D->C
E->another way of asking this is whether you can create a summary table in Discoverer at a higher level than a dimension's fundamental grain. In other words - the summary examples in the documentation all describe leaving out one or more of your dimensions... they are either left in or completely taken out. But, some of the most effective summarization occurs when you summarize daily data to a monthly level. Assuming that I have a sales table (at a daily level, and a key value sales_date), and a table date_dim (primary key sales_date), I would like to create a summary sales_month_summary where the sales are grouped on month_year (which is a field in the sales_date table).
How is this done? I suspect that we can't use the date_dim table with the summary (due to the problems noted by the poster above). Do we have to create another table "month_dim"? Do we have to fold all of the desired date attributes (month, quarter, year) into the summary? Obviously we'd like to re-use all of the pertinent already existing date items (quarter, month, year, etc.), not recreate them over again, which would result in essentially two sets of items in the EUL. [One used for this month summary, and another used for the detail.]
I searched the forum - someone asked this same question back in 2000 - there was no answer provided.
The only other thought I have is to "snowflake" the date_dim into two tables and two folders, one at a date level, another at the month level. Then the detail tables can connect to date_dim (which is linked to month_dim), while the summary data can connect directly to month_dim. -
Hello Experts,
I had a issue where we are executing one custom report in which i used inner join on table MKPF & MSEG, some time join statement took 9-10 min to excute and some time execute within 1-2 min with same test data .
i am not able to understand what the actaully happing .
please help.
code :
SELECT f~mblnr f~mjahr f~usnam f~bktxt p~bukrs
INTO TABLE itab
FROM mkpf AS f INNER JOIN mseg AS p
ON f~mblnr = p~mblnr AND f~mjahr = p~mjahr
WHERE f~vgart = 'WE'
AND f~budat IN p_budat
AND f~usnam IN p_sgtxt
AND p~bwart IN ('101','105')
AND p~werks IN p_werks
AND p~lgort IN p_lgort.
Regards,
Dipendra Panwar.Hi Dipendra,
if you call a report twice after another with the same test data for data selection, then the second run should be faster, because some data are remaining in memory and needn't to be caught from database. This will be also for the following third und further runs, until the data in the SAP memory will be removed by other programs.
For performance traces you should try to test with a first run.
Regards,
Klaus -
Left outer join 3 tables with where-statement
Hi folks,
I hope you can understand (and maybe solve) my problem.
Generally I try to left outer join three tables. The third table is used for a WHERE-statement.
The three table structures are the following:
table 1 (user)
user1 | key
table 2 (detail)
key | ID
table 3 (header)
ID | user2
...and I want to achieve the following structure (as example filled with data):
user | key | ID
|-----|----
xy | a | 001
xy | b | #
z | b | #
The clue ist the usage of the third table. I need the table to set user1 and user2 equal (WHERE) but there are two problems:
1) Obviously I can't left outer join two tables with each other. In this case I already used the 'key' of table 1 to join it with the 'key' of table 2. So I can't left outer join the 'ID' of table 2 with the 'ID' of table 3. Error message that I can only left outer join a table once. Any proposals?
2) I have to include a WHERE to equal user1 with user2. But I am not allowed to use the user2 from table 3 because of the left outer join.
I tried this coding:
SELECT auser1 akey b~id INTO TABLE itab FROM ( table1 AS a
LEFT OUTER JOIN table2 AS b ON akey = bkey )
LEFT OUTER JOIN table3 AS c ON bID = cID )
WHERE auser1 = cuser2.
I would really appreciate your help.
Regards
MrclSpdlIF you want to join a DB table with an internal table, you need to use the 'FOR ALL ENTRIES' statement.
select dbfields
into table itab2
from dbtab
for all entries in itab
where dbfield1 = itab-field1.
This will get you a second internal table with all the corresponding data for the first selection. You can then join them with a loop through the first table and a read table on the second table (for 1 - 1 relation) or a nested loop statement on both tables (for 1 - N relation). Make itab a hashed table when using read table with key, use a sorted table if you need to loop without key access.
Regards,
Freek -
Hi,
I have a query that joins two tables in the same database, the result needs to be loaded in a destination DB table. How do I do this in SSIS package?
thank you !
Thank You Warmest Fanny PiedPlease take a look at these links related to your query.
http://stackoverflow.com/questions/5145637/querying-data-by-joining-two-tables-in-two-database-on-different-servers
http://stackoverflow.com/questions/7037228/joining-two-tables-together-in-one-database -
JOIN 2 tables that have same column ?
I need to learn how to join two tables that both have the same column name:
tbl1 - idskey
tbl2 - idskey
the idskey column holds a id_number
When I do the JOIN I would like to make sure that only Distinct records are joined from both tables and that any duplicates are removed in the final join. So if:
Tbl1 has a idskey of: 12345
and
Tbl2 has a idskey of: 12345
In the final JOIN I want to remove one of those duplicates.
I actually need to join 3 tables that have the same linking column names for the join, but if I learn how to do this correctly on 2, that will be a start.
10g for db, thanks!Hi,
SELECT DISTINCT and GROUP BY are the most common ways to get unique results from non-unique keys. Exactly how you use them depends on exactly what you want to do.
SELECT DISTINCT guarantees that no two rows in the result set, conisdering all columns, will be identical.
GROUP BY produces one row from a set of rows that have a common feature. The values on that row may be a composite of values from various rows in that set (e.g., an average).
Please post a small, specific example. For instance:
"I have two rows in tbl1 ...
and these fhtee rows in tbl2 ...
Notice how there is one row with idskey=12345 in tbl1 but two such rows in tbl2.
How can I get theses results ...
where only one row has idskey=12345?" -
Joining a table with all_tab_columns
How is it possible to join a table with the tab_columns?
The query im trying to establish is that in my table they are 12 columns with months names. So under an input variable im trying to return the required values with the selected months. The only way i could think of to get the months to connect with the tab_columns table.
Any suggestion is really appreciated
SELECT bust,
Sum(jan) JAN,
Sum(feb) FEB,
Sum(mar) MAR,
Sum(apr) APR,
Sum(may) MAY,
Sum(jun) JUN,
Sum(jul) JUL,
Sum(aug) AUG,
Sum(sep) SEP,
Sum(oct) OCT,
Sum(nov) NOV,
Sum(DEC) DECC
FROM budget a,all_tab_columns b
WHERE vsl_code = 4602
AND code = 1
AND year=2013
AND account_code='30'
AND b.table_name='BUDGET'
AND b.column_name IN
(SELECT column_name
FROM (SELECT Column_name, ROWNUM r
FROM all_tab_columns b
WHERE table_name = 'BUDGET'
AND Column_id BETWEEN 3 AND 14
ORDER BY column_id)
WHERE r BETWEEN 2 AND 3 ) --Returns February,March
group by bust;Sorry, I don't understand what you're trying to do or why you think you need to join to all_tab_columns. Perhaps you could post the definition of the budget table, some sample data, and the results you're hoping to see.
Without that, I don't see why you can't just do this:
SELECT bust,
Sum(jan) JAN,
Sum(feb) FEB,
Sum(mar) MAR,
Sum(apr) APR,
Sum(may) MAY,
Sum(jun) JUN,
Sum(jul) JUL,
Sum(aug) AUG,
Sum(sep) SEP,
Sum(oct) OCT,
Sum(nov) NOV,
Sum(DEC) DECC
FROM budget a
WHERE vsl_code = 4602
AND code = 1
AND year=2013
AND account_code='30'
group by bust; -
Joining Two Tables with Total Amount
Hi All,
I'm trying to join to tables P02 and P30 on the invoice no fields but getting duplicates. In table P30 we need to sum the payment column per invoice to get the actual payment amount. This then needs to Join to table P02. I have uploaded sample
data on this link and provided an example on how the output should like.
https://app.box.com/s/pu8oa4f3jhrhm0ylshdz2fuo7541vn4z
Thanks
JagI figured out why the duplicates appear. I'm attaching another table supplier to fill in the missing propcode when running the query below
SELECT P02.P02_UNIQUE, p30.PROP_CODE, P02.SUPP_ALPHA+P02.SUPP_NUMERIC As SupplierCode, P02.INV_ALPHA+P02.INV_NUMERIC AS InvoiceNo,TotalPayment, Year, Month
FROM P02
CROSS APPLY (
SELECT PROP_CODE, SUM(TOTAL_AMOUNT) AS TotalPayment, P30.INVOICE_NUMB, DATEPART(year,[CREATED_DATE_SQL]) AS [Year], DATEName(Month,[CREATED_DATE_SQL]) AS [Month]
FROM dbo.P30
WHERE P02.INV_ALPHA+P02.INV_NUMERIC = P30.INVOICE_NUMB
GROUP BY PROP_CODE, COST_CENTRE, DATEPART(year,[CREATED_DATE_SQL]), DATEName(Month,[CREATED_DATE_SQL]), P30.INVOICE_NUMB
)P30
Where P02.SUPP_ALPHA+P02.SUPP_NUMERIC = '668'
Result below and the last row the prop_code is missing
I have another table supplier which has the suppliercode and propcode so was trying to use the prop_code field from supplier table instead of P30 table to fill in the gap. But when i do that i get duplicates and wrong values.
I have updated the sample data with supplier table. -
Hi Gurus,
I have three tables. I want to join all tables using union in SQL statement. The query is returning all the records from both tables but i only require unique rows based on a specific column value. Here is my table structure -
TableA -
LIC_ID NUMBER(10) NOT NULL
LIC_NUMBER VARCHAR2(20)
COMMENCE_DATE DATE
EXPIRY_DATE DATE
TERM VARCHAR2(20)LIC_ID is the primary key in this table -
Sample data from TableA
LIC_ID LIC_NUMBER COMMENCE_DATE EXPIRY_DATE TERM
2 TR4323 12/04/2008 11/03/2010 2 Years
34 TR5432 23/07/2009 22/07/2010 1 Year
45 TR5321 24/06/2009 23/06/2010 1 Year
65 TR6666 23/07/2010 22/07/2011 1 Year
32 TR2423 30/05/2010 29/05/2011 1 YearTableB -
MAR_ID NUMBER(10) NOT NULL
LIC_ID NUMBER(10) NOT NULL
ZONE_NAME VARCHAR2(20)
DEPARTMENT VARCHAR2(20)
ACTIVITIES VARCHAR2(200)
COMMENTS VARCHAR2(200)MAR_ID is the primary key in this table and LIC_ID is the foreign key on TableA
Sample data from TableB -
MAR_ID LIC_ID ZONE_NAME DEPARTMENT ACTIVITIES COMMENTS
23 2 ZONE A IT NONE
43 34 ZONE B IT NONE
33 65 ZONE C ACCOUNT NONE
TableC
REC_ID NUMBER(10) NOT NULL
LIC_ID NUMBER(10) NOT NULL
DIST_NAME VARCHAR2(20)
REGION VARCHAR2(20)
ACTIVITIES VARCHAR2(200)
COMMENTS VARCHAR2(200)REC_ID is the primary key in this table and LIC_ID is the foreign key.
Sample data -
REC_ID LIC_ID DIST_NAME REGION ACTIVITIES COMMENTS
2 45 SA NORTH NONE
3 65 TA NORTH NONE
5 32 NT SOUTH NONEHere is my sql query -
select a.lic_id, a.lic_number, a.commence_date, a.expiry_date from
TableA a, TableB b
where a.lic_id=b.lic_id
union
select a.lic_id, a.lic_number, a.commence_date, a.expiry_date from
TableA a, TableC c
where a.lic_id=c.lic_idThe above query returns -
lic_id lic_number commence_date expiry_date
2 TR4323 12/04/2008 11/03/2010
34 TR5432 23/07/2009 22/07/2010
45 TR5321 24/06/2009 23/06/2010
65 TR6666 23/07/2010 22/07/2011
32 TR2423 30/05/2010 29/05/2011
65 TR6666 23/07/2010 22/07/2011 LIC_ID 65 exists in both table TableB and TableC hence it repeats in query but I want to display that only once. How can I do that? I want to return unique record on LIC_NUMBER.
Hope this make sence.
Many thanks,
TajuddinThanks for all your reply and suggestions. David altering session did not work.
Sven your idea helped me to figure it out what to do. I found a way around to fix it. Here is my current code -
select a.lic_id, a.lic_number, a.commence_date, a.expiry_date from
TableA a, TableB b
where a.lic_id=b.lic_id
union
select a.lic_id, a.lic_number, a.commence_date, a.expiry_date from
TableA a, TableC c
where a.lic_id=c.lic_id and c.lic_id not in ( select lic_id from TableB)This will exclude any LIC_ID exists in TableB.
Thanks again for your help guys.
Regards,
M Tajuddin
Web: http://tajuddin.whitepagesbd.com
Blog: http://aspblog.whitepagesbd.com -
No Easy Way to Join on Tables from Different Schemas
Hi,
The company policy does not allow to join on tables from different schemas or use db links...
I'm tasked to come up with a Perl script that does exactly that - allows for the SELECT statement to do several joins on 3 different schemas. In addition 1 of the schemas is on the different host altogether.
Upping the privileges for my user and allowing db links is not an option...Can someone, please help me to understand on a conceptual level how would I use Perl and what logic would it have and what would it (perl) do?
Thank you,Court in the wrong job... ;)
It's like a librarian who is a hard rock artist maintaining the silence in the premises. ;)
My dear friend, i don't think this is the right place for your requirement. This is the PL/SQL forum. If you have any problem related PL/SQL or SQL you can place that here.
Regards.
Satyaki De.
Maybe you are looking for
-
Distiller error from Indesign EPS-file
I cannot generate a pdf in distiller pro 9 from a EPS generated by Indesign CS4. The EPS is quite large (2.32GB) both in filesize as in dimension (177cm wide by 40cm) Can anybody help me out here? thanks Wim The errorlog is Distilling: pan01.eps Star
-
Dynamic Pie Chart in Smart Form
Hi Frn's , How can i show the dynamic Pie chart in Smartform . Thanks and Regards Priyank Dixit
-
Photoshop Elements 13 - Costco Special Edition
I purchased Photoshop Elements 13 from Costco however my CD/DVD drive isn't working. I have an expired trial version of elements installed on my laptop. I know that I can use the serial number to reactivate the trial version but I was wondering if th
-
TS4006 cant see the device on find my iphone
cant see the device on find my iphone. please help.
-
My cinema 4d lite won't open when I click on it, how do I get it to open?
nothing has expired, I upgrade all the programs, I just can't get it to open when I click on it, please help