3 tables with left joins - bug?
Hello,
i am making query where i encounter problem with left join in oracle. I am using oracle 10g and i prepare simple test case.
he is testing tables and datas - really simple i think:
drop table t1;
drop table t2;
drop table t3;
create table t1 (a number not null);
create table t2 (a number, b number);
create table t3 (b number);
insert into t3 values (1);
insert into t3 values (2);
insert into t3 values (3);
insert into t1 (a) values (1);
insert into t2 (a,b) values (1,1);
insert into t1 (a) values (2);
insert into t2 (a,b) values (2, null);
insert into t1 (a) values (3);
insert into t1 (a) values (4);
insert into t2 (a,b) values (4,1);
insert into t1 (a) values (5);
insert into t2 (a,b) values (5,3);
and now query with left joins:
select
t1.a
, t2.a, t2.b
, t3.b
from
t1, t2, t3
where
t1.a = t2.a (+)
and t2.b = t3.b (+)
and t3.b is null
order by t1.a
i get two rows as result:
A A_1 B B_1
2 2 null null
3 null null null
i expect these rows but when i change my query - i dont want get back t3.b column:
select
t1.a
, t2.a, t2.b
/* , t3.b*/
from
t1, t2, t3
where
t1.a = t2.a (+)
and t2.b = t3.b (+)
and t3.b is null
order by t1.a
i get only one row
A A_1 B
2 2 null
My question is simple how can i only by changing columns getting back change number of returned rows? I must say i dont expect these result i expect two rows again.
Thanks for help.
BluShadow wrote:
I think I know what you are getting at.
By testing for null on t3.b when you aren't selecting the column, you are enforcing oracle to perform the join through t2 onto t1, but Oracle can't join because t2 has no matching row (although it's outer joined to t1) and therefore, for the one row it can't actually determine if t3.b is null or not, so that row can't match the conditions in a "true" sense and be displayed. If you select the column then oracle can test its nullness ok. (Perhaps this is a bug, I don't know, it's just how I know it works)If you get different results only by changing the projection part of the query this is a bug and nothing else. I can't reproduce using Oracle 10g XE, I get in both cases shown the expected two rows.
What versions are you using to test this?
SQL>
SQL> select * from v$version
2 where rownum <= 1;
BANNER
Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
SQL>
SQL> drop table t1 purge;
Table dropped.
SQL> drop table t2 purge;
Table dropped.
SQL> drop table t3 purge;
Table dropped.
SQL>
SQL> create table t1 (a number not null);
Table created.
SQL> create table t2 (a number, b number);
Table created.
SQL> create table t3 (b number);
Table created.
SQL>
SQL> insert into t3 values (1);
1 row created.
SQL> insert into t3 values (2);
1 row created.
SQL> insert into t3 values (3);
1 row created.
SQL>
SQL> insert into t1 (a) values (1);
1 row created.
SQL> insert into t2 (a,b) values (1,1);
1 row created.
SQL>
SQL> insert into t1 (a) values (2);
1 row created.
SQL> insert into t2 (a,b) values (2, null);
1 row created.
SQL>
SQL> insert into t1 (a) values (3);
1 row created.
SQL>
SQL> insert into t1 (a) values (4);
1 row created.
SQL> insert into t2 (a,b) values (4,1);
1 row created.
SQL>
SQL> insert into t1 (a) values (5);
1 row created.
SQL> insert into t2 (a,b) values (5,3);
1 row created.
SQL>
SQL> commit;
Commit complete.
SQL>
SQL> select t1.a
2 , t2.a, t2.b
3 , t3.b
4 from
5 t1 left outer join t2 on (t1.a = t2.a)
6 left outer join t3 on (t2.b = t3.b)
7 where t3.b is null
8 order by t1.a;
A A B B
2 2
3
SQL>
SQL> select t1.a
2 , t2.a, t2.b
3 -- , t3.b
4 from
5 t1 left outer join t2 on (t1.a = t2.a)
6 left outer join t3 on (t2.b = t3.b)
7 where t3.b is null
8 order by t1.a;
A A B
2 2
3
SQL>Regards,
Randolf
Oracle related stuff blog:
http://oracle-randolf.blogspot.com/
SQLTools++ for Oracle (Open source Oracle GUI for Windows):
http://www.sqltools-plusplus.org:7676/
http://sourceforge.net/projects/sqlt-pp/
Similar Messages
-
Testing for IS NOT NULL with left join tables
Dear Experts,
The query is showing the NULL rows in the query below....
Any ideas, advice please? tx, sandra
This is the sql inspector:
SELECT O100321.FULL_NAME_LFMI, O100321.ID, O100404.ID, O100321.ID_SOURCE
, O100404.NAME, O100321.PERSON_UID, O100404.PERSON_UID, O100404.VISA_TYPE
FROM ODSMGR.PERSON O100321
, ODSMGR.VISA O100404
WHERE ( ( O100321.PERSON_UID = O100404.PERSON_UID(+) ) ) AND ( O100404.VISA_TYPE(+) IS NOT NULL )Hi Everyone,
I am understanding alot of what Michael and Rod wrote.... I am just puzzled over the following:
the query below is left joining the STUDENT table to
HOLD table.
The HOLD table - contains rows for students who have holds on their record.
a student can have more than one hold (health, HIPAA, basic life saving course)
BUT, for this query: I'm only interested that a hold exists, so I'm choosing MAX on hold desc.
Selecting a MAX, helps me, bec. it reduces my join to a 1 to 1 relationship, instead of
1 to many relationship.
Before I posted this thread at all, the LEFT JOIN below testing for IS NOT NULL worked w/o
me having to code IS NOT NULL twice....
Is that because, what's happening "behind the scenes" is that a temporary table containing all max rows is being
created, for which Discoverer has no predefined join instructions, so it's letting me do a LEFT JOIN and have
the IS NOT NULL condition.
I would so appreciate clarification. I have a meeting on Tues, for which I have to explain LEFT JOINS to the user
and how they should create a query. I need to come up with rules.
If I feel "clear", I asked my boss to buy Camtasia videocast software to create a training clip for user to follow.
Also, if any Banner user would like me to email the DIS query to run on their machine, I would be glad to do so.
thx sooo much, Sandra
SELECT O100384.ACADEMIC_PERIOD, O100255.ID, O100384.ID, O100255.NAME, O100384.NAME, O100255.PERSON_UID, O100384.PERSON_UID, MAX(O100255.HOLD_DESC)
FROM ODSMGR.HOLD O100255, ODSMGR.STUDENT O100384
WHERE ( ( O100384.PERSON_UID = O100255.PERSON_UID(+) ) ) AND ( O100384.ACADEMIC_PERIOD = '200820' )
GROUP BY O100384.ACADEMIC_PERIOD, O100255.ID, O100384.ID, O100255.NAME, O100384.NAME, O100255.PERSON_UID, O100384.PERSON_UID
HAVING ( ( MAX(O100255.HOLD_DESC(+)) ) IS NOT NULL )
ORDER BY O100384.NAME ASC -
JPA OnetoMany QUERY LEFT JOIN BUG
Using JPA in JDev 10.1.3.1.0.3984
Database: Firebird 1.51LI-V1.5.3.4870 Firebird 1.5/tcp
Driver: Jaybird JCA/JDBC driver Version: 2.1
TopLink, version: Oracle TopLink Essentials - 2006.8 (Build 060829)
If I use normal JOIN it works.
On LEFT JOIN I get a {oj [/b] before the table name and a [b]} at the end.
public class Cliente{
@OneToMany(mappedBy = "cliente")
@JoinColumn(name = "CDCLIENTE", referencedColumnName = "CDCLIENTEREQUISITANTE")
private List<Requisicao> requisicoes;
public class Requisicao
@ManyToOne
@JoinColumn(name = "CDCLIENTEREQUISITANTE", referencedColumnName = "CDCLIENTE")
private Cliente cliente;
EntityManager em = getEntityManager();
String sql = "SELECT c FROM Cliente c LEFT JOIN c.requisicoes req";
Query q = em.createQuery(sql);
List rs = q.getResultList();Result SQL:
SELECT DISTINCT t0. <OMITTED> FROM {oj [/b]CLIENTE t0 LEFT OUTER JOIN REQUISICAO t1 ON (t1.CDCLIENTEREQUISITANTE = t0.CDCLIENTE)[b]}You cannot define an ON clause with Criteria, nor JPQL.
Perhaps you can reword the query to avoid needing an ON clause.
What is the query you want to do (in english)?
Can you just use an OR in the where clause?
There is a enhancement request to have ON clause support added, please vote for it.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=312146
James : http://www.eclipselink.org -
How to generate a query involving multiple tables(one left join others)
Hi, all,
I want to query a db like these:
I need all the demographics information(from table demo) and their acr info(from table acr), and their clinical info(from table clinical), and their lab info(from table lab).
The db is like this:
demo->acr: one to many
demo->clinical info: one to many
demo->lab info: one to many
I want to get one query result which are demo left join acr, and demo left join clinical, and demo left join lab. I hope the result is a record including demo info, acr info, clinical info, and lab info.
How could I do this in SQL?
Thanks a lot!
QianThank you very, very much!
Actually, I need a huge query to include all the tables in our db.
We are running a clinical db which collects the patients demographics info, clinical info, lab info, and many other information.
The Demographics table is a center hub which connects other tables. This is the main architecture.
My boss needed a huge query to include all the information, so others could find what they need by filtering.
As you have found, because one patients usually has multiple clinical/lab info sets, so the result will be multiplied! the number of result=n*m*k*...
My first plan is to set time point criteria to narrow all the records with one study year. If somebody needs to compare them, then I have to show them all.
So I have to know the SQL to generate a huge query including as many tables as possible.
I show some details here:
CREATE TABLE "IMMUNODATA"."DEMOGRAPHICS" (
"SUBJECTID" INTEGER NOT NULL,
"WORKID" INTEGER,
"OMRFHISTORYNUMBER" INTEGER,
"OTHERID" INTEGER,
"BARCODE" INTEGER,
"GENDER" VARCHAR2(1),
"DOB" DATE,
"RACEAI" INTEGER,
"RACECAUCASIAN" INTEGER,
"RACEAA" INTEGER,
"RACEASIAN" INTEGER,
"RACEPAC" INTEGER,
"RACEHIS" INTEGER,
"RACEOTHER" VARCHAR2(50),
"SSN" VARCHAR2(11),
PRIMARY KEY("SUBJECTID") VALIDATE
CREATE TABLE "IMMUNODATA"."ACR" (
"ID" INTEGER NOT NULL,
"THEDATE" DATE ,
"SUBJECTID" INTEGER NOT NULL,
"ACR_PAGENOTCOMPLETED" VARCHAR2(1000) ,
"ACR_MALARRASHTODAY" INTEGER ,
"ACR_MALARRASHEVER" INTEGER ,
"ACR_MALARRSHEARLIESTDATE" DATE ,
PRIMARY KEY("ID") VALIDATE,
FOREIGN KEY("SUBJECTID") REFERENCES "IMMUNODATA"."DEMOGRAPHICS" ("SUBJECTID") VALIDATE
CREATE TABLE "IMMUNODATA"."CLIN" (
"ID" INTEGER NOT NULL,
"THEDATE" DATE ,
"SUBJECTID" INTEGER NOT NULL,
"CLIN_PAGENOTCOMPLETED" VARCHAR2(1000) ,
"CLIN_FATIGUE" VARCHAR2(20) ,
"CLIN_FATIGUEDATE" DATE ,
"CLIN_FEVER" VARCHAR2(20) ,
"CLIN_FEVERDATE" DATE ,
"CLIN_WEIGHTLOSS" VARCHAR2(20) ,
"CLIN_WEIGHTLOSSDATE" DATE ,
"CLIN_CARDIOMEGALY" VARCHAR2(20) ,
PRIMARY KEY("ID") VALIDATE,
FOREIGN KEY("SUBJECTID") REFERENCES "IMMUNODATA"."DEMOGRAPHICS" ("SUBJECTID") VALIDATE
Other tables are alike.
Thank very much!
Qian -
Query 4 joined tables with internal joins to represent a complex hierarchy!
I've got to refine/replace a query (Oracle 9i) that
currently joins rows from four tables in a hierarchical
fashion that I use to produce a listing like this:
agency abc 1
....division def 1.1
........service ghi 1.1.1
........service jkl 1.1.2
............faq mno 1.1.2.1
............faq pqr 1.1.2.2
........service stu 1.1.3
....division vwx 1.2
........service yyy 1.2.1
............faq zzz 1.2.1.1
The change involves allowing for unlimited levels of
nested child divisions to produce a listing like this:
agency abc 1
....division def 1.1
........service ghi 1.1.1
........service jkl 1.1.2
............faq mno 1.1.2.1
............faq pqr 1.1.2.2
........service stu 1.1.3
....division vwx 1.2
........division xxx 1.2.1
............division aaa 1.2.1.1
............division bbb 1.2.1.2
................service aaa 1.2.1.2.1
....................faq fff 1.2.1.2.1.1
....................faq ggg 1.2.1.2.1.2
........service yyy 1.2.1
............faq zzz 1.2.1.1
Notice the insertion of three nested divisions under
division 1.2 with services and faqs under those. The
order of names throughout is alphabetic within a nesting
level.
Here's the SQL I currently use, without nested divisions
(it contains extra info that I use to control what and
how names are displayed):
SELECT
agency.agency_id AGENCY_ID,
agency.agency_type_id AGENCY_TYPE_ID,
agency.name AGENCY_NAME,
agency.acronym AGENCY_ACRONYM,
agency.expiration_date AGENCY_EXP,
agency.post_count AGENCY_POST,
agency.stat AGENCY_STAT,
agency_type.agency_type AGENCY_TYPE,
division.division_id DIV_ID,
division.name DIV_NAME,
division.transfer_number DIV_TRANS_NUM,
division.expiration_date DIV_EXP,
division.post_count DIV_POST,
division.stat DIV_STAT,
service.service_id SVC_ID,
service.name SVC_NAME,
service.taxonomy SVC_TAX,
service.keywords SVC_KEYWORDS,
service.action_type SVC_ACTION_TYPE,
service.sr_form_name SVC_SR_FORM,
service.expiration_date SVC_EXP,
service.post_count SVC_POST,
service.stat SVC_STAT,
faq.faq_id FAQ_ID,
faq.name FAQ_NAME,
faq.expiration_date FAQ_EXP,
faq.post_count FAQ_POST,
faq.stat FAQ_STAT
FROM
agency,
agency_type,
division left join service on
division.division_id=service.division_id left join
faq on service.service_id=faq.service_id
WHERE (
(agency_type.agency_type_id = agency.agency_type_id)
AND (agency.agency_id = division.agency_id)
AND (agency.agency_id = :agency_id )
It's very fast -- I can retrieve and display 5,000 rows
in seconds using Perl DBI and CGI -- and very easy to use
to produce the hierarchical listing of items from the
four tables. It is also very straightforward since I was
able to generate the SQL using the SQL modeler in TOAD
(I'm not the strongest SQL developer so I resort to
tools).
I need to get jump-started in the right direction to
determine what I need to add to my division table
(div_parent_id?), if I need a div_parent_child table to
define the relationships (rows with parent_id & child_id
pairs), and how to change or rewrite the SQL query. The
CGI form that will be used to define the relationships
will ask users to define children of a given division. I
envision presenting a list of divisions with null
parent_division_id columns for users to select from then
updating selected rows for selected divsions.
Thanks in advance for any help/guidance!
-GeneINLINE VIEWS!
select whatever_you_want
from (
SELECT FOLDER_ID, PARENT_FOLDER_ID, FOLDER_NAME
FROM FOLDERS
START WITH PARENT_FOLDER_ID = 0 CONNECT BY PARENT_FOLDER_ID = PRIOR FOLDER_ID
) tree, FILES
where tree.folder_id = files.folder_id -- or something like that
always try to keep the CONNECT BY limited to ONE AND ONLY table. then use that query in a subquery, a WITH clause, an inline view or something. do not try to JOIN or UNION with a CONNECT BY. it won't work the way you think it will, and even it returns the expected results, it will perform terribly.
* your mileage may vary
Message was edited by:
shoblock
added exclamation marks to show my excitement!!!! -
How to use common object from two tables with out join.
HI,
I have two tables called A & B In A table i have the following objects
1.weekend
2.S1(measure)
3.S2(measure)
4.S3(measure)
5.S4(measure)
And In B table i have followning columns
1.week end
2.p1(measure)
3.p2(measure)
4.p3(measure)
5.p4(measure)
Now in universe i created all the measure objects i.e.s1,s2,s3,s4,p1,p2,p3,p4 A.weekend,B.weekend.
instead of using week end two times i wnt to use only once because this is common in both table.
if i use join between these tables i am getting values fine
But With out join is there any thing to do in universe level to create common objects to use from both the tables..I tried using aggregate awareness but while reporting it is taking as two SQL.which is not synchronized.
Please help me on this ...hi,
Although Weekend column is present in both tables, by creating a single Object in Universe, Universe can identify relationship with only table referenced in Object Creation.
So, there will be no identification of relationship with other table measures.
Obviously, you need to create 2 Weekend objects in Universe (in two classes).
Case 1: You need not join these two tables in Universe. When you create 2 Queries in WEBI, automatcially Weekend objects are synchronized (if both are of same datatype)
Case 2: If you join these two tables in Universe, Obviously,
your SQL may contain Weekend from Table1, measures from Table 2
or
your SQL may contain Weekend from Table2, measures from Table 1
Finally, You need to create 2 objects in Universe. But your query may contain a single Object based on Case 2.
Regards,
Vamsee -
Can we join 3 tables with left outer join
hi friends.
Can any one tell how to join 3 tables using <b>left outer join</b>...i tried by taking some fields of <b>ekko,ekpo,eket</b>, but this not working ... plz give a sample code with some fields.Hi Uday
<b>Inner joins using 3 tables </b>
<i><b>Try this :-</b></i>
SELECT stpo~stlnr stpo~idnrk mast~matnr mara~mtart stpo~menge
INTO CORRESPONDING FIELDS OF TABLE zmat1 FROM mast
JOIN stpo ON stpo~stlnr = mast~stlnr
JOIN mara ON mara~matnr = mast~matnr
WHERE stpo~stlty = 'M' "AND stpo~idnrk IN s_matnr
AND mast~werks = 1000.
<b><i>Here s_matnr is a select-options on the selection-screen. </i></b>
<i><b>Or this. </b></i>
<b>Code: </b>
Select single Vbrk~Bukrs Vbrk~Kunrg Vbrk~Vbeln
Vbrk~Fkdat Vbrk~Bstnk_Vf Vbrk~Zterm
Tvzbt~Vtext
Vbak~Vbeln Vbak~Bstdk
Likp~Vbeln Likp~lfdat Likp~Lfuhr
into w_vbrk
from vbrk
inner join Tvzbt on Tvzbt~Zterm = Vbrk~Zterm and
Tvzbt~Spras = sy-langu
Inner join Vbfa as SalesLnk
on SalesLnk~vbeln = pu_vbeln and
SalesLnk~vbtyp_v = c_order
inner join Vbak on Vbak~Vbeln = SalesLnk~Vbelv
Inner join Vbfa as DeliveryLnk
on DeliveryLnk~vbeln = pu_vbeln and
DeliveryLnk~vbtyp_v = c_Delivery
inner join Likp on Likp~Vbeln = DeliveryLnk~Vbelv
where vbrk~vbeln = pu_Vbeln.
<i><b>This code locates sales, delivery and payment terms info from a billing document number.</b></i>
<i><b>or</b></i>
<b>
Here, this one also works fine :</b>
select zfpcd~cadivi zfpcd~proforma zfpcd~factura zfpcd~aniofactura
zfpcd~montousd zfpcd~montoap zfpcd~ebeln zfpcd~inco1
zfpcd~lifnr lfa1~name1 zcdvs~status zfpcd~conint
into it_lista
from zfpcd inner join zcdvs
on zfpcd~ebeln = zcdvs~ebeln
and zfpcd~proforma = zcdvs~proforma
and zfpcd~lifnr = zcdvs~lifnr
inner join lfa1
on zfpcd~lifnr = lfa1~lifnr
where zcdvs~status = '04'.
Reward if helpfull
Regards
Pavan -
How to delete a row from a SQL Server CE Table with multiple JOINs?
I want to delete a record from a SQL Server CE table.
There are 3 tables scripts, options and results. I would like to remove a record from the results table. The where clause contains dynamic information which retrieved via other queries to different tables in the same database. These queries work fine and deliver
the desired data.
The Compact server is a clone of a remote table created using the sync framework. The same query to the remote table works fine.
The error I get is:
There was an error parsing the query. [ Token line number = 1,Token line offset = 10,Token in error = from ]
The code that throws the exception is as follows:
Dim connLoc As SqlCeConnection = New SqlCeConnection(My.Settings.ConnectionString)connLoc.Open() Dim strDel As String = "Delete r from ResultsTable r inner join OptionsTable o ON o.TestName=r.TestName inner join ScriptTable c ON r.TestName=c.TestName WHERE r.TestName = '" & ds1Loc.Tables(0).Rows(0)(1) & "' AND [Index] = '" & lstIndex & "'"Dim cmdDel As SqlCeCommand = New SqlCeCommandcmdDel.CommandText = strDelcmdDel.Connection = connLoccmdDel.ExecuteNonQuery()
The values held in ds1Loc.Tables(0).Rows(0)(1) and lstIndex are
correct so should not be the problem.
I also tried using parameterised queries
Dim strDel As String = "Delete r from [ResultsTable] r inner join [OptionsTable] o ON o.TestName=r.TestName inner join [ScriptTable] c ON r.TestName=c.TestName WHERE r.TestName = @TestName AND [Index] = @lstIndex"
Dim cmdDel As SqlCeCommand = New SqlCeCommand cmdDel.CommandText = strDel
With cmdDel.Parameters
.Add(New SqlCeParameter("@TestName", ds1Loc.Tables(0).Rows(0)(1)))
.Add(New SqlCeParameter("@lstIndex", lstIndex))
End With
cmdDel.Connection = connLoc cmdDel.ExecuteNonQuery()
I have tried replacing the "=" with "IN" in the the WHERE clause but this has not worked.
Is it the join that is causing the problem? I can do a select with the same search criteria and joins from the same database.
Also this query works with SQL Server. Is it perhaps that SQL CE does not support the Delete function the same as SQL Server 2008? I have been looking at this for a while now and cannot find the source of the error. Any help would be greatly appreciated.Hello,
In SQL Server Compact, we can use join in FROM clause. The DELETE statement fail may be caused by the FOREIGN KEY constraint.
Please refer to:
DELETE (SQL Server Compact)
FROM Clause (SQL Server Compact)
Regards,
Fanny Liu
Fanny Liu
TechNet Community Support -
How to refresh a table with multiple joins
Hi,
First at all, I'm newby in ADF, and my english is no so good, sorry for that...
I'm using JDeveloper 11g Release 2 (11.1.2.3.0). I have a table created from a view object that have multiple joins with other entities. When I insert a new row programmatically in one of the entities of the joins (not in the entitiy of the view object itself), the new row is created in the database correctly but the table don't show it. What can I do to refresh the table to see the new row created?
Thanks in advance!You have to update the iterator the table is based on for the ui last. You do that by executing the query on the iterator again.
Timo -
Upgraded reports with left join no longer working in Visual Studio 2008
I've upgraded an ASP.NET project, which has lots of reports, from Visual Studio 2003 to Visual Studio 2008. Any reports that contain a left outer join relationship no longer work and it's driving me mad as I've spent hours on this now. Basically, the join fails because there's no rows on the right side of the relationship. I'm checking for nulls in the formula's and there's no record selection criteria. The report is pulling data from 2 stored procedures and a couple of tables. Any ideas?
Hi Ludek,
Thanks for your reply. I've already applied SP1 and I assumed it worked, but looking at it in depth I'm not so sure. The installer runs and says its configuring windows etc and it l looks like it finishes, but it doesn't display a message to say installation was successful. When I look in the event log there are warnings during the install, I don't know if I should be worried about them. They are as follows:
Error in Template (C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\Web\VisualBasic\1033\AdoNetEntityDataModelVB_ASPNET.zip), file (ModelObjectItemVB_ASPNET.vstemplate). Invalid template element (TemplateID) value (Microsoft.Data.Entity.Design.VSTemplate.ModelObjectItemVB_ASPNET)
Error in Template (C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\Web\VisualBasic\1033\AdoNetDataServiceVBWebsite.zip), file (WebDataService.vstemplate). Unknown attribute (_locID).
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
As for the report itself, Its connecting to SQL Server and getting the data from 2 stored procedures and a few tables. There are no errors reported in the report, the only warning we have is when you close the database expert it says:
"More than one datasource or a stored procedure has has been used in this report. Please make sure that no SQL expression is added and no server-side group-by is performed." We've always had that message and it's never caused any problems before. -
How do i join 3 table with the 'join' query ?
Hello,
i want to join 3 tables -> bsis, bsad and vbrp
the components of the query to be are ,
- select (matnr from vbrp) sum(amount from bsad).
- join bsis and bsad on bsisbukrs = bsadbukrs, bsisbelnr = bsadaugbl and bsisbldat = bsadaugdt.
- where bsisblart = 'DZ' and bsishkont = '123456'.
- join bsad and vbrp on vbrpburks = bsadbukrs, vbrpgjahr = bsadgjahr and vbrpbelnr = bsadbelnr.
The double join query is to be constructed out of the above components.
Thanks,
Shehryar Daharc an example....
DATA: BEGIN OF wa,
carrid TYPE spfli-carrid,
connid TYPE spfli-connid,
fldate TYPE sflight-fldate,
bookid TYPE sbook-bookid,
END OF wa,
itab LIKE SORTED TABLE OF wa
WITH UNIQUE KEY carrid connid fldate bookid.
SELECT pcarrid pconnid ffldate bbookid
INTO CORRESPONDING FIELDS OF TABLE itab
FROM ( ( spfli AS p
INNER JOIN sflight AS f ON pcarrid = fcarrid AND
pconnid = fconnid )
INNER JOIN sbook AS b ON bcarrid = fcarrid AND
bconnid = fconnid AND
bfldate = ffldate )
WHERE p~cityfrom = 'FRANKFURT' AND
p~cityto = 'NEW YORK' AND
fseatsmax > fseatsocc.
LOOP AT itab INTO wa.
AT NEW fldate.
WRITE: / wa-carrid, wa-connid, wa-fldate.
ENDAT.
WRITE / wa-bookid.
ENDLOOP.
Ramesh. -
Updating a table with self join
Hi Experts
have a table & data as shown below
read_date
reading
consum
20140915
1000
20140916
NULL
120
20140917
NULL
80
20140918
NULL
100
20140919
1400
as per the requirement missing reading should be updated using reading+consum, and i should get missing readings as 1120,1200,1300 respectively. have tried below query, but its updating just one row.
UPDATE c1 SET reading=c1.consumption+ISNULL(c2.reading,0) FROM @CW_data c1 JOIN @CW_data c2 ON DATEADD(d,-1,c1.read_date)=c2.read_date WHERE c1.reading IS NULL
Please advise.
Thanks & Regards,
ShivaPlease post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. You failed. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. Could tell us why you are special and the rules do not apply to you? Here is my guess at what a polite person would have posted.
CREATE TABLE Foobar_Meters
(reading_date DATE DEFAULT CURRENT_TIMESTAMP NOT NULL
PRIMARY KEY,
foo_reading INTEGER
CHECK( foo_reading >= 0));
What you are trying to do is a running total. Put it in a view so it is always correct:
INSERT INTO Foobar_Meters
VALUES
('2014-09-15', 1000),
('2014-09-16', 120),
('2014-09-17', 80),
('2014-09-18', 100),
('2014-09-19', 0);
CREATE VIEW Cumulative_Readings
AS
SELECT reading_date, foo_reading,
SUM(foo_reading)
OVER (ORDER BY reading_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS foo_reading_cum
FROM Foobar_Meters;
>> have tried below query [sic], but its updating just one row. <<
An UPDATE is not a query. Learn the correct terms. And you used the old Sybase UPDATE..FROM.. syntax!! Google it! It does not work!And you used the old ISNULL and not COALESCE().
Back in the days of punch cards, we kept such data in the physical card because we had to!
You have done the wrong thing, the wrong way. The only technique worse would be a cursor.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Doubt Regarding LEFT JOIN Operation
Hello,
With the Old syntax in place it is easier for find that which join is performed on which table ...
But with the new syntax ..m getting bit confused when INNER & LEFT JOINS used together ...
Below is the FROM clause ...please explain .. how this JOIN is gonna take place ..& which table is Left joined with whom...
FROM VW_TRANS_MANAGER_SALES ref_1
LEFT OUTER JOIN VW_AGREE_ASSIGN_TAG_DTLS ass
ON Trim(ass.agreement_id) = trim(ref_1.AGREEMENT_ID)
LEFT OUTER JOIN VW_CURENT_RATING_DTLS CURR
ON (ref_1.company_code =curr.COMPANYCODE)
LEFT OUTER JOIN VW_PREV_RATING_DETAILS PREV
ON (ref_1.company_code =prev.COMPANYCODE)
LEFT OUTER JOIN CRMADMIN.CO_MA_COMPANY_CONTACTS cont
ON (ref_1.CLIENT_CONTACT_ID= cont.CONTACT_ID)
LEFT OUTER JOIN CRMADMIN.COR_CRM_MST_CITY city
ON (city.City_id= cont.City_id))
---------------------------------------------------------------------------------------------------------------------------------------Hi,
Aijaz Mallick wrote:
Yeah .. but was a bit Confusing as u used 2 columns in each table....
Doesn't it depends on the joining condition we use ... lets Say ..if i use an INNER join after 2 LEFT join ... & m doing an that inner join with the first SOURCE table .... then will it perform a join on the resultset on the previous Joins...???Sorry, I'm not sure what you're asking.
Please post a specific example of a join that you don't understand, or some results that you don't know how to get.
Use commonly available tables (like those in the scott or hr schemas) or post your own CREATE TABLE and INSERT statements.
Using ANSI syntax, the results are as if the joins were done in the order they appear in the FROM clause (even though the optimizer may not actually do them in that order).
For example, in the querry below, the inner-join between emp and salgrade is done first, then the outer join with dept is done to that result set.
SELECT d.dname
, e.ename
, g.losal
FROM scott.emp e
JOIN scott.salgrade g ON e.sal BETWEEN g.losal
AND g.hisal
RIGHT OUTER JOIN scott.dept d ON e.deptno = d.deptno
;Output:
DNAME ENAME LOSAL
ACCOUNTING CLARK 2001
ACCOUNTING MILLER 1201
ACCOUNTING KING 3001
RESEARCH FORD 2001
RESEARCH SCOTT 2001
RESEARCH JONES 2001
RESEARCH ADAMS 700
RESEARCH SMITH 700
SALES BLAKE 2001
SALES ALLEN 1401
SALES MARTIN 1201
SALES WARD 1201
SALES JAMES 700
SALES TURNER 1401
OPERATIONSNotice that the OPERATIONS department, which has no matches in the other tables, is still included because of the outer join.
If you want to have the joins done in a different order, you can explicitly join some table first, either in a sub-query or just by grouping joins within parentheses in the same FROM clause, as in the query below (which produces the same results as the query above):
SELECT d.dname
, e.ename
, g.losal
FROM scott.dept d
LEFT OUTER JOIN ( -- Join the following tables first:
scott.emp e
JOIN scott.salgrade g ON e.sal BETWEEN g.losal
AND g.hisal
) ON d.deptno = e.deptno
; -
Hi all,
Hoping you can help me with my SQL query. I want to do a
simple LEFT JOIN between two tables...fair enough right? Yeah,
well, it works and all rows are returned from the LEFT table even
if there are nmo matching rows in the RIGHT table.
BUT, when I apply a few conditions using WHERE after this
LEFT JOIN the whole point of the LEFT JOIN seems to not work. I
only get rows from the LEFT where they match in the RIGHT.
For example...this following code works and returns all LEFT
rows despite there not being a match in the RIGHT.
<cfquery name="getSchemaFields" datasource="#request.dsn#"
username="#request.username#" password="#request.password#">
SELECT schema_#getSchemas.schema_token#_fields.*,
fields_content.*
FROM schema_#getSchemas.schema_token#_fields
LEFT JOIN fields_content
ON schema_#getSchemas.schema_token#_fields.field_type_uuid =
fields_content.field_content_field_uuid
</cfquery>
But, what I really need is to apply some conditions on the
rows I want from the right table based on an ID like as follows...
<cfquery name="getSchemaFields" datasource="#request.dsn#"
username="#request.username#" password="#request.password#">
SELECT schema_#getSchemas.schema_token#_fields.*,
fields_content.*
FROM schema_#getSchemas.schema_token#_fields
LEFT JOIN fields_content
ON schema_#getSchemas.schema_token#_fields.field_type_uuid =
fields_content.field_content_field_uuid
WHERE fields_content.field_content_item_id = <cfqueryparam
cfsqltype="cf_sql_integer" value="#getSchemas.item_id#" />
OR fields_content.field_content_item_id = NULL
AND fields_content.field_content_item_uuid = <cfqueryparam
cfsqltype="cf_sql_varchar" value="#getSchemas.item_uuid#" />
OR fields_content.field_content_item_uuid = NULL
</cfquery>
Now I don't get any errors but what I do get is rows from the
left ONLY when they match rows in the RIGHT. I still need all the
rows from the LEFT despite this. The WHERE conditions seems to stop
this happening.
I know it's probably blindingly simple but I just can't get
my head around it and I'm pulling my hair out about it!
Hope somebody can assist me in this.
Many thanks in advance!!
Mikey.> Now I don't get any errors but what I do get is rows
from the left ONLY when
> they match rows in the RIGHT. I still need all the rows
from the LEFT despite
> this. The WHERE conditions seems to stop this happening.
You need to stop to think about how the query is being
executed.
FIRST the FROM recordset is created which is the result of
the join
statement. This will have all your "left" rows, and null-data
for
unmatched "right" rows.
THEN the WHERE clause is executed, which will filter out any
rows from the
recordset create in the FROM recordset.
So if yuor data is this:
TBL_FRUIT
FRT_ID, FRT_NAME
1, Apple
2, Banana
3, Cherry
TBL_STOCK (<sung>we have no bananas, we have no bananas
today</sung>)
STK_ID, FRT_ID, STK_LEVEL
1, 1, 12
2, 3, 100
And if you FROM clause is this:
from TBL_FRUIT F left outer join TBL_STOCK S on F.FRT_ID =
S.FRT_ID
You get a record set thus:
1, Apple, 12
2, Banana, null
3, Cherry, 100
Now if you have a WHERE filter, thus:
WHERE S.STK_LVEL > 0
You're going tobe filtering out the banana row, because it
DOESN'T have a
STK_LEVEL > 0
1, Apple, 12
3, Cherry, 100
You need to get all your filtering done on the STOCK table
*before*
left-joining it to the FRUIT table, if you want to have all
the fruit rows
in the final result.
Dan's detailed how to effect this.
Make sense?
Adam -
Error While mapping table with 100 Columns
Hello
Actually i had a requirement in which i have to map the data into target table from more than 50 tables with complex join conditions
So I created 5 maps separately to load the data and now i am feared that while i deploy the the first map the other columns which doesnt have a map
will be filled with nulls and some of the columns have unique constraint on it so its giving me error
Please Help me out i need to submit my Assignment by Monday
Thanks
SriksBharadwaj Hari wrote:
Hi,
I agree with u...I am not sure of the environment the user has so i put forth all the 3 option that crossed my mind that time....thats why i said he has to choose what best suits him/her...
Also if the database is huge and we create physical temp tables (option 2 and ur idea) its like having redundant data in the database which is also a problem....So ist upto the user to actually evaluate the situation and come up with what best suits him/her...
Regards
BharathHi,
I understand your opinion. But I am not sure that the user have enough experience to choose the best option by his one. And about the redundant data: because of this I wrote that he should truncate the tables after the last mapping which loads all data into the real target table.
Regards,
Detlef
Maybe you are looking for
-
HT4356 I have a Kodak printer hero 9.1 and can't get it to work with my I pad is there a way
Hello I can't get my iPad to work with the Kodak hero 9.1 does anyone have any suggestions thanks
-
[SOLVED] Confused about development packages
To build an embedded linux image using minifs utility, I need to install some development packages. The packages listed in the tutorial are named for Debian based distros, with the "-dev" suffix. Some of the listed packages are: libz-dev, libelf-dev,
-
Publish to hard drive mirroring folder structure
Hello, The publish to hard drive feature was one of my most anticipated additions in LR3. I use this to maintain a backup of all my images with the edits baked in, which offers a great level of security. My only disappointment is that it flattens the
-
Hello I am looking for some guidance; I have 4 clips shot simultaneous of a subject; from 4 different angles. I would like to make a clip that is "interactive". The clip start from the shot head on and the viewer can click and have the clip continue
-
Building Web Based VoIP Phone using Flex
Hi, all. I want to build a sip client web based using Adobe Flex. Anyone can tell me how I start? By the way, I use Asterisk as communication server. In other discussion, I find the google alchemy, but I still don't know what it is. Please your answe