Subquery
I have a question about SQL. I need to remove duplicates from result set. I need to use DISTINCT in WHERE clause with both - VARCHAR-type text field and CLOB text field. DISTINCT does not work with CLOB.
I can use dbms_lob.substr with CONTAINS, but I need another way around.
Could I use DISTINCT in WHERE clause with both - VARCHAR-type text field and CLOB text field BUT in subquery?
Is 'subquery" option another way around in order to remove dupes from result set and what is the best way to do it?
Thank you for your help.
If you use the DBMS_CRYPTO.HASH function you can compare clobs if you just want to know if they are the same or different.
Similar Messages
-
Can't view the sheets when using subquery in discoverer desktop
Hi All,
I have created 5 subqueries sheets and I need the data from sheet1, sheet3, sheet5. But in the main sheet when I choose the subquery sheets, its showing only 3 sheets(i.e., sheet1, sheet2, sheet4). I don't want the data from sheet2 and sheet4 but I want from sheet1,3,5. I can't view the sheet3,5.
Please advice.
Thanks,
KamalI use Image Converter for iPad to convert my Sony RAW file.
Not sure if it'll work for Canon. -
TWO ERRO ORA-01427: single-row subquery returns more than one row
Hi,
I have a procedure which contains a cursor. If i run the select statement in the cursor separetly, it returns only value and works fine. But the same select statement in the cursor of a procedure throws me the error as below:
TWO ERRO ORA-01427: single-row subquery returns more than one row
Not sure what going on...any help appreciated.
Below is the select statement:
SELECT DISTINCT PSE.PARENT_POSITION_ID,
(SELECT DISTINCT PPD1.SEGMENT2
FROM PER_POSITION_DEFINITIONS PPD1,
HR_ALL_POSITIONS_F HAPF2,
PER_POS_STRUCTURE_ELEMENTS PSE2
WHERE TRUNC(SYSDATE) BETWEEN
HAPF2.EFFECTIVE_START_DATE AND
HAPF2.EFFECTIVE_END_DATE
AND PPD1.POSITION_DEFINITION_ID =
HAPF2.POSITION_DEFINITION_ID
AND
HAPF2.POSITION_ID = PSE2.PARENT_POSITION_ID
AND PSE2.PARENT_POSITION_ID =
PSE.PARENT_POSITION_ID
AND ROWNUM = 1) SEGMENT2,
(SELECT DISTINCT PAPF1.FIRST_NAME || ' ' ||
PAPF1.LAST_NAME CHIEF_NAME
FROM PER_ALL_PEOPLE_F PAPF1,
PER_ALL_ASSIGNMENTS_F PAAF1
WHERE TRUNC(SYSDATE) BETWEEN
PAPF1.EFFECTIVE_START_DATE AND
PAPF1.EFFECTIVE_END_DATE
AND TRUNC(SYSDATE) BETWEEN
PAAF1.EFFECTIVE_START_DATE AND
PAAF1.EFFECTIVE_END_DATE
AND PAAF1.POSITION_ID = PSE.PARENT_POSITION_ID
AND PAPF1.PERSON_ID = PAAF1.PERSON_ID
AND ROWNUM = 1) CHIEF_NAME
FROM PER_POS_STRUCTURE_ELEMENTS PSE,
HR_ALL_POSITIONS_F HAPF,
PER_POSITION_DEFINITIONS PPD
WHERE PSE.SUBORDINATE_POSITION_ID = 52744
AND TRUNC(SYSDATE) BETWEEN HAPF.EFFECTIVE_START_DATE AND
HAPF.EFFECTIVE_END_DATE
AND HAPF.POSITION_ID = PSE.SUBORDINATE_POSITION_ID
AND HAPF.POSITION_DEFINITION_ID = PPD.POSITION_DEFINITION_ID;
Thanks
PK
Edited by: user539616 on Jun 30, 2009 6:30 PMHi,
The cursor has a different parameter? Maybe the query is not exactly the same. Could you check this?
This is your query (formatted):
SELECT DISTINCT PSE.PARENT_POSITION_ID,
(SELECT DISTINCT PPD1.SEGMENT2
FROM PER_POSITION_DEFINITIONS PPD1,
HR_ALL_POSITIONS_F HAPF2,
PER_POS_STRUCTURE_ELEMENTS PSE2
WHERE TRUNC(SYSDATE) BETWEEN HAPF2.EFFECTIVE_START_DATE AND
HAPF2.EFFECTIVE_END_DATE
AND PPD1.POSITION_DEFINITION_ID = HAPF2.POSITION_DEFINITION_ID
AND HAPF2.POSITION_ID = PSE2.PARENT_POSITION_ID
AND PSE2.PARENT_POSITION_ID = PSE.PARENT_POSITION_ID
AND ROWNUM = 1) SEGMENT2,
(SELECT DISTINCT PAPF1.FIRST_NAME || ' ' || PAPF1.LAST_NAME CHIEF_NAME
FROM PER_ALL_PEOPLE_F PAPF1,
PER_ALL_ASSIGNMENTS_F PAAF1
WHERE TRUNC(SYSDATE) BETWEEN PAPF1.EFFECTIVE_START_DATE AND
PAPF1.EFFECTIVE_END_DATE
AND TRUNC(SYSDATE) BETWEEN PAAF1.EFFECTIVE_START_DATE AND
PAAF1.EFFECTIVE_END_DATE
AND PAAF1.POSITION_ID = PSE.PARENT_POSITION_ID
AND PAPF1.PERSON_ID = PAAF1.PERSON_ID
AND ROWNUM = 1) CHIEF_NAME
FROM PER_POS_STRUCTURE_ELEMENTS PSE,
HR_ALL_POSITIONS_F HAPF,
PER_POSITION_DEFINITIONS PPD
WHERE PSE.SUBORDINATE_POSITION_ID = 52744
AND TRUNC(SYSDATE) BETWEEN HAPF.EFFECTIVE_START_DATE AND HAPF.EFFECTIVE_END_DATE
AND HAPF.POSITION_ID = PSE.SUBORDINATE_POSITION_ID
AND HAPF.POSITION_DEFINITION_ID = PPD.POSITION_DEFINITION_ID;Tips: To put formatted code you must use {noformat}{noformat} tags, start tag and end tag are the same,you don't need to put '/' in the close tag.
Regards, -
Subquery in IF statement in trigger, without using foreign keys
Hello,
I'm investigating ways of writing a subquery in an IF statement, which is placed inside a trigger.
I wanna write smth like IF (:new.jazz not in (select goldies from T where ... )) etc. I don't know whether the fact that the IF is in a trigger adds some additional restrictions. (Does it?)
So far I found the solution described here: SubQuery Comparison in If Statement which I find a bit tacky, I could have the 'cooleststarinthegalaxy' instead of 1 and seems you need to do extra light, but still extra lifting.
I also read about the possibility of using MERGE, which I'm currently researching.
Is there any other way?
Thanks
Edited by: BluShadow on 14-Nov-2012 13:37
fixed link
Edite by me: the question is how (if possible) to do this without a foreign key.
Edited by: questioningq12 on Nov 14, 2012 6:11 AM
Edited by: questioningq12 on Nov 14, 2012 6:13 AMHi,
questioningq12 wrote:
Say I have tables A(namea varchar(10)), B(nameb varchar(10)), and B contains tuples ('1stname','2ndname').
I wrote a trigger before insertion, for each row, on table A. For a tuple t to be inserted, it should check whether t.namea is in the set of values nameb from B.
E.g., INSERT INTO A VALUES('1stname') should work. But INSERT INTO A VALUES ('3rdname') should fail. You can use a foreign key constraint for that.
If the tables already exist, and b.nameb is declared as UNIQUE (or PRIMARY KEY), then you can say:
ALTER TABLE a
ADD CONSTRAINT a_namea_fk
FOREIGN KEY (namea)
REFERENCES b (nameb)
;If you had a situation where you really needed to query a table in PL/SQL, and you weren't sure if the query would find anything, you could put the query in its own BEGIN ... EXCEPTION block, and test for NO_DATA_FOUND.
If you're just checking to see if a row exists or not, you can always write a query that is guaranteed to return exactly 1 row, like this:
BEGIN
SELECT COUNT (*)
INTO x
FROM b
WHERE nameb = :NEW.namea
AND ROWNUM = 1;
IF x = 0
THEN
... -- print msgs, raise exceptions etc
END IF;
END;Edited by: Frank Kulash on Nov 14, 2012 9:22 AM
Added example -
How to model in OWB if you have a subquery in your select statement? (11.2)
Which operator (is it the Table operator) to use if I have a subquery as part of my select statement? (The way I do it works, but is not elegant. What I do is create a table for the subquery and than join that with the other sources to point to my target.) But, would appreciate the best way with OWB's features.
Here is the entire SQL (including the subquery):
SELECT to_numbe (null), course_id
at.book, lp.NAME,
(select b.pricing from qp_pricing_attributes b
where b.list_id = ll.list_id and b.product = at.product) sign,
ll.operand AS price, lhb.comments
FROM
pricing_attribs at,
list_lines ll,
list_h lp,
list_b lhb
WHERE 1 = 1
and ll.list_line_id = atrib.list_line_id
AND ll.list_header_id = lp.list_header_id
AND lp.list_header_id = lhb.list_header_id
Thanks you.Hi
Doesn't need to be a table in the target. Let's take a very simple example, let's say you wanted to do the following;
select ename,(select dname from dept d where d.deptno=e.deptno) from emp e
Then DEPT is your lookup table and EMP is your driving table.
1. Add EMP on to the canvas.
2. Add in lookup operator
3. Bind lookup to DEPT
4. Hit finish
5. Map EMP.DEPT to DEPT.INGRP1 (the lookup operator)
6. Edit lookup operator, on Lookup Conditions tab set DEPTNO for lookup column, and DEPTNO for input attribute
7. Lookup complete now
You can add in a target table operator and map from the source EMP table and the output attributes of the lookup operator. you can change step 4 to carry on through wizard and define lookup, but I have chosen to do 5, to automatically get the names and datatypes of the inputs. There are lot of other options now in 11gR2 in the lookup.
Hope this makes sense.
Cheers
David -
Subquery returned more than one value
Hi,
I have this statement which has been working fine - not I get a 'Subquery returned more than one value" error:
SELECT
'WAS3' AS 'Rec ID',
E.EecEEID AS 'Emp ID',
eepNameFirst AS 'First Name',
eepNameLast AS 'Last Name',
EecDateOfOriginalHire AS 'Service Date',
(SELECT DATEDIFF(YEAR, EecDateOfOriginalHire, getdate()) from empcomp EC WHERE EC.EecEEID = E.EECEEID) as 'Yrs of Serv'
FROM
EmpPers
JOIN EmpComp E
ON E.eecEEID = eepEEID
JOIN Company
ON eecCoID = cmpCoID
WHERE
EecDateOfTermination IS NOT NULL
AND EXISTS
(SELECT 1
FROM EmpComp e2
WHERE e2.EecEEID = E.EecEEID
--AND e2.eecEmplStatus <> 'A')-- changed to <> ...this WAS/is to filter out anyone that was termed then re-hired
--AND E.EecTermReason NOT IN ('I01','I02','I03','I14','I22','V05','V07','V09','V12','V22','V13', 'TRO')
AND E.eecDateOfTermination
IN (SELECT (EC.eecDateOfTermination)
FROM EMPCOMP EC
WHERE EC.EecEEID = E.EECEEID
AND EC.eecDateOfTermination IS NOT NULL
AND eC.eecDateOfTermination >= DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0)
AND EC.eecDateOfTermination <=DATEADD(wk,DATEDIFF(wk,0,GETDATE()),6)
AND e.eecDateOfTermination >= DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0)
AND E.eecDateOfTermination <= DATEADD(wk,DATEDIFF(wk,0,GETDATE()),6)))
--AND eC.eecDateOfTermination >= DATEADD(wk,DATEDIFF(wk,0,('12/30/2007')),0)
-- AND EC.eecDateOfTermination <=DATEADD(wk,DATEDIFF(wk,0,('12/30/2007')),6)
-- AND e.eecDateOfTermination >= DATEADD(wk,DATEDIFF(wk,0,('12/30/2007')),0)
-- AND E.eecDateOfTermination <= DATEADD(wk,DATEDIFF(wk,0,('12/30/2007')),6)
-- AND E.eecDateOfTermination IS NOT NULL ))
--added below per Paul Cottle to exclude employeess less than four years
AND E.eecdateoforiginalhire >=dateadd(year,-4, CURRENT_TIMESTAMP)
qeqwCheck this, if it works:
SELECT
'WAS3' AS 'Rec ID',
E.EecEEID AS 'Emp ID',
eepNameFirst AS 'First Name',
eepNameLast AS 'Last Name',
EecDateOfOriginalHire AS 'Service Date',
DATEDIFF(YEAR, EecDateOfOriginalHire, getdate()) as 'Yrs of Serv'
FROM EmpPers
JOIN EmpComp E ON E.eecEEID = eepEEID
JOIN Company ON eecCoID = cmpCoID
WHERE EecDateOfTermination IS NOT NULL
AND EXISTS
(SELECT 1
FROM EmpComp e2
WHERE e2.EecEEID = E.EecEEID
AND E.eecDateOfTermination
IN (SELECT (EC.eecDateOfTermination)
FROM EMPCOMP EC
WHERE EC.EecEEID = E.EECEEID
AND EC.eecDateOfTermination IS NOT NULL
AND eC.eecDateOfTermination >= DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0)
AND EC.eecDateOfTermination <=DATEADD(wk,DATEDIFF(wk,0,GETDATE()),6)
AND e.eecDateOfTermination >= DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0)
AND E.eecDateOfTermination <= DATEADD(wk,DATEDIFF(wk,0,GETDATE()),6)))
AND E.eecdateoforiginalhire >=dateadd(year,-4, CURRENT_TIMESTAMP)
If this post answers your query, please click "Mark As Answer" or "Vote as Helpful". -
Need Help in creating a subquery using JOIN operation
Hi,
I am new to SQL and trying to write a query. Please help me in this.
The Database Schema looks like this:
The database scheme consists of four tables:
Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)
Laptop(code, model, speed, ram, hd, screen, price)
Printer(code, model, color, type, price)
The table "Product" includes information about the maker, model number, and type ('PC', 'Laptop', or 'Printer'). It is assumed that model numbers in the Product table are unique for all the makers and product types. Each PC uniquely specifying by a code in the table "PC" is characterized by model (foreign key referencing to Product table), speed (of the processor in MHz), total amount of RAM - ram (in Mb), hard disk drive capacity - hd (in Gb), CD ROM speed - cd (for example, '4x'), and the price. The table "Laptop" is similar to that one of PCs except for the CD ROM speed, which is replaced by the screen size - screen (in inches). For each printer in the table "Printer" it is told whether the printer is color or not (color attribute is 'y' for color printers; otherwise it is 'n'), printer type (laser, jet, or matrix), and the price.
Alternatively you can refer here for the schema (Computer Firm)
http://www.sql-ex.ru/help/select13.php#db_1
Now my query is :
Find the makers of the cheapest color printers.
Result set: maker, price.
and I have written the query as:
SELECT prod.maker, prin.* FROM (SELECT MIN(price) AS price FROM printer WHERE color = 'y') AS prin INNER JOIN (SELECT maker, model FROM product) AS prod ON prin.model = prod.model
Which is giving the error "Invalid column name 'model'.". Please help!
Thanks!
FaazHello,
Your query does not work because your subquery prin does not return a column named model.
Analytical functions like Vivek L suggests are the best way to do this, but this one is a correction of your query and should work too (not tested, unfortunately).
SELECT prod.maker, prin2.*
FROM (SELECT MIN(price) AS min_price FROM printer WHERE color = 'y') AS prin
INNER JOIN (SELECT model, price FROM printer WHERE color='y' ) AS prin2 ON prin.min_price = prin2.price
INNER JOIN (SELECT maker, model FROM product) AS prod ON prin2.model = prod.model;Regards,
Sylvie -
How to Do This In a Join Not A Subquery
I have two tables:
USERS
user_id
fname
lname
USER_SITES
user_id
site_id
confirmed
There is a one to many relationship between USERS and USER_SITES (a user can belong to many sites).
I am looking for a query that will return only users who are a member of site_id=2, not site_id=4. The following subquery does the trick:
select * from USERS where user_id in (select user_id from USER_SITES where site_id=2) and user_id not in (select user_id from USER_SITES where site_id=4);
...but I would like to do this using only JOINS (they are generally faster....and also its kind of frustrating me that I cannot figure out how to do it in a join).Second attempt.
with users as
select 1 as user_id, 'a' as fname, 'b' as lname from dual union all
select 2 as user_id, 'a' as fname, 'b' as lname from dual union all
select 3 as user_id, 'a' as fname, 'b' as lname from dual
user_sites as
select 1 as user_id, 2 as site_id from dual union all
select 2 as user_id, 4 as site_id from dual union all
select 3 as user_id, 2 as site_id from dual union all
select 3 as user_id, 4 as site_id from dual
-- end of test data
select user_id, fname, lname from
select u.user_id,
u.fname,
u.lname,
max(site_id) over (partition by u.user_id) as m
from users u
join user_sites s on u.user_id = s.user_id
where s.site_id in (2,4)
where m = 2;
USER_ID FNAME LNAME
1 a b Edited by: Cyn on Feb 23, 2010 2:46 PM
Edited by: Cyn on Feb 23, 2010 3:02 PM -
Add subquery to main query in Report Builder 6i
Usually, when you add a subquery to an existing query in a report, you'll see the query in data model marked by a paper clip icon with a forward slash across it (means "Subquery Inside"). All current field names in current query (except CF and CS) will have a '1' appended after it (CF and CS fields are not affected), but in your sql, the column names stay the same. So there is an out-of-sync situation with the column names.
To fix this:
1) before change anything, back up old report somewhere else
2) copy the original query somewhere else as backup
3) open the query in Report Builder
4) wipe out the query, replace it by "select 1 from dual" to reset it and press ok.
5) replace "select 1 from dual" with your new query with an embedded subquery.
6) All field names will be without the '1' appendix.
7) check all the CS fields, the source should be reset to null. Redefine the CS fields using backed up report as reference. CF fields are not affected.
8) move the fields and restore the break orders according to backed up report.
9) Recompile whole report.
10) save report again and you're done.
Maybe you don't need this in the latest version of Report Builder, but in 6i, this is what I do.If you use aliases for your item names in your original query you avoid this problem....
eg
Select field1 item1, field2 item2 from table.....
item 1 and item2 will stay in your layout between query changes.
D -
Report Issue - A subquery filter may not reference the current report
Hi,
I a, trying to create a drill down report - I am getting below error when I drill down from summary report to detail -
A subquery filter may not reference the current report (or contain a circular reference to any report).
Error Details
Error Codes: S6C66RYK:WIF3IYGO
Recursion limit exceeded in Xml Expression Visitor
The issue is I have a budget report which will drill down to display amount by each period -
Jan-10 Feb-10 Mar-10
1223 123 10
Now I am trying to display detail GL transactions by clicking the amount field.
This means summary report should pass period along with amount to display detail GL transactions.
Please help me to resolve this issue.
Thanks,
PoojakExplain exactly how you create your 2 reports.
The second one must have "is prompted" filters if you want it to use the values of the first one. -
BW 3.5 Subquery variable
I am working with BW3.5. I have many variables that are created by replacement path from a subquery. I currently have the problem that if I need to check the name of the subquery used by a variable I have to do a change variabel.When I do this the system sometimes comes back with a response "Specify a Technical Name" in a box named SAPVarEditor and after clicking OK the Query name in the Replacement Path area is blank. Anyone know what causes this?
Hi Armin
I am having the same SAPVarEDitor dialog pop-up on my BW3.5 system (copy of BW production) for some of the variables. It's not happening on the BW production system though. I thought you may have a solution for your question, if so, if you can kindly post them to me ..
much appreciated..
Seong -
How can i use multiple row subquery in update statement
Hai All
I using group function in my update statement.. and i need to update more rows so i need to use multiple row
subquery pls tell me how to use multiple row subquery in update statement
For example
while i am using this like this i got an error
update dail_att set outtime in (select max(r2.ptime) from temp_att where empcode=r2.enpno and
barcode=r2.cardn and attend_date=r2.pdate group by enpno,pdate,cardn);
Pls tell me how to use with example
Thanks & regards
Srikkanth.MHai Man
Thanks for ur response Let me clear what i need
First step Fetch the records as text file and stores into table T1
and the next step is i have seperated the text using substring and stores in different columns of a table
There are two shifts 0815 to 1645 and 1200 and 2000
Here I rep IN and O rep OUT
Empno date time inout
001 01-01-10 0815 I
002 01-01-10 0815 I
003 01-01-10 0818 I
001 01-01-10 1100 0
001 01-01-10 1130 I
002 01-01-10 1145 0
002 01-01-10 1215 I
004 01-01-10 1200 I
005 01-01-10 1215 I
004 01-01-10 1315 O
004 01-01-10 1345 I
001 01-01-10 1645 0
002 01-01-10 1715 0
003 01-01-10 1718 0
004 01-01-10 2010 0
005 01-01-10 2015 0
This is my T1 table i have taken data from text file and stored in this table from this table i need to move data to another table T2
T2 contains like this
Empno Intime Intrin Introut Outtime Date
001 0815 1100 1130 1645 01-01-10
002 0815 1145 1215 1715 01-01-10
003 0818 1718 01-01-10
004 1200 1315 1345 2010 01-01-10
005 1215 2015 01-01-10
This what i am trying to do man but i have little bit problems Pls give some solution with good example
And my coding is
declare
emp_code varchar2(25);
in_time varchar2(25);
out_time varchar2(25);
Cursor P1 is
Select REASON,ECODE,READMODE,EMPD,ENPNO,FILL,PDATE,PTIME,INOUT,CARDN,READERN
From temp_att
group by REASON,ECODE,READMODE,EMPD,ENPNO,FILL,PDATE,PTIME,INOUT,CARDN,READERN
ORDER BY enpno,pdate,ptime;
begin
for r2 in p1 loop
declare
bar_code varchar2(25);
begin
select barcode into bar_code from dail_att where empcode=r2.enpno and attend_date=r2.pdate;
For r3 in (select empcode,empname,barcode,intime,intrin,introut,addin,addout,outtime,attend_date from dail_att)loop
if r2.inout ='O' then
update dail_att set outtime =(select max(r2.ptime) from temp_att where empcode=r2.enpno and barcode=r2.cardn and attend_date=r2.pdate group by r2.cardn,r2.enpno,r2.pdate );
end if;
end loop;
exception
when no_data_found then
if r2.inout ='I' then
insert into dail_att(barcode,empcode,intime,attend_date)(select r2.cardn,r2.enpno,min(r2.ptime),r2.pdate from temp_att group by r2.cardn,r2.enpno,r2.pdate );
end if;
end;
end loop;
commit;
end;
Pls tell me what correction i need to do i the update statement i have used a subquery with group function but when i used it will return only one row but my need is to return many rows and i need to use multiple row subquery
and how can i use it in the update statement
Thanks In Advance
Srikkanth.M -
How can I remove distinct from subquery?
Hello, I'll expose my problem, I don't know if may be is a bug.
Suppose We have
Table A:
field A1 primary key
field A2
field A3
Table B
field B1 primary key
field B2 foreig key to A(A1)
field B3
I use reverse tool to build objects from DB schema.
Everything runs ok but when I want to recover A objects
with sum(B3) from B,it doesn't runs fine.
To achieve this I've made a class C with fields of class A and a double
for sum. The code I've use is:
KodoQuery query = (KodoQuery)getPersistenceManager()
.newQuery(A.class, "this == b.b2");
query.declareVariables("B b");
query.declareImports("x.x.B");
query.setResultClass(C.class);
query.setResult("this as a, sum(b.b3) as s");
query.setGrouping("a");
Collection c = query.execute();
I use PostGreSQL 7.4, and the sql that Kodo generates is like this:
SELECT s.A1, SUM(s.C) AS c
FROM ( SELECT DISTINCT a.A1 AS A1, s.B3 AS C
FROM PUBLIC.A a INNER JOIN PUBLIC.B b ON (a.A1 = b.B2) ) s
GROUP BY s.A1
But the problem is 'DISTINCT' keyword. If I have records on B
with same B3 value then:
B1=1,B2=1,B3=25
B1=2,B2=1,B3=25
The query returns SUM(B3)=25 which is not valid!!!, it must be 50.
It fails with repeated B3 values because distinct keyword.
I bypass this adding a third field to class C that I will not use, and
introduce it into query:
KodoQuery query = (KodoQuery)getPersistenceManager()
.newQuery(A.class, "this == b.b2");
query.declareVariables("B b");
query.declareImports("x.x.B");
query.setResultClass(C.class);
query.setResult("this as a, sum(b.b3) as s, sum(b.b1) as t");
query.setGrouping("a");
Collection c = query.execute();
With this, I force to put primary key into subquery, and disables
DISTINCT, but I never will use this field :(. SQL generated by KODO:
SELECT s.A1, SUM(s.C) AS c, SUM(s.T) as t
FROM ( SELECT DISTINCT a.A1 AS A1, s.B3 AS C, s.B1 as T
FROM PUBLIC.A a INNER JOIN PUBLIC.B b ON (a.A1 = b.B2) ) s
GROUP BY s.A1
Questions:
1.- What may I doing wrong?
2.- How can I disable Distinct from subquerys?
And, no, I don't want to select by class B and then search A objects.
I want a C object with A object plus SUM of values from B.
I am achieving this with this patch.
I know that when there aren't B objects I don't receive results.
Is there any way to build an OUTER JOIN with JDOQL ?
In order to bypass this, I execute the query another time but reseting to
0, but I will prefer to be able to build an OUTER JOIN ;)
PD: Little class descriptions:
class A{ int a1, int a2, int a3} (autogenerated by kodo)
class B{ int b1, int b2, double b3} (autogenerated by kodo)
class C{ A a, double c, int t} (generated by me)
Sorry for my english :(
thanks.I'll address your outer join question first, since it's the easiest. Kodo will
create outer joins automatically as needed to satisfy your JDOQL. In this case,
your JDOQL does not warrant an outer join. Your filter criteria on the query is
"this == b.b2". That means the query cannot and should not return any values
when there are no A's that match that join. Why not try this equivalent but
simpler query?
Query q = pm.newQuery (B.class);
q.setResult ("b2 as a, sum(b3) as s");
q.setGrouping ("b2");
q.setResultClass (C.class);
That will return results grouped by the A objects from the b2 field, and the sum
of the b3 field for all B's in each group. It should use an outer join.
About DISTINCT:
The pattern of a distinct subselect is caused by two conditions:
1. Your result clause is non-distinct. That is, you did:
q.setResult("this as a, sum(b3) as s")
rather than:
q.setResult("distinct this as a, sum(b3) as s")
This means that you want to allow duplicates in the projected values you get back.
2. You use an unbound variable ("b") in a way that could lead to duplicates
caused by relational joins. JDO always eliminates duplicates caused by database
joins.
So in order to eliminate the possible duplicates caused by #2, Kodo issues the
query as a DISTINCT subselect. Then in order to allow duplicates of the
projected results (#1), Kodo uses a non-distinct outer select.
The simplest way to eliminate the DISTINCT subselect is to use the alternate
query on B.class I mentioned above. That will result in no DISTINCTs at all.
Another way is to use the "distinct" keyword in your setResult() call, as I
showed in #1. That will result in a DISTINCT select without any subselect.
Without reverting to a SQL query (which you can still execute through JDO APIs,
as described in the documentation), I believe those are the options available. -
Designer support for Subquery against SAP BW Bex Query
BusinessObjects designer has an option in the paramaters window to turn on "Allow Sub-Queries" in a universe that has been created using a olap source. SAP BW BEX Query to be specific. Once turned on, you can build a query and the subquery button and functionality is actually enabled and allows you to build it. When running the query I get an error message "A filter contains a wrong value. You cannot run this query".
Now, I am pretty sure this functionality is not supported on a BW or OLAP source but, I can not find anything definitive from SAP stating that it is not supoorted. So I want to make sure that this is not one of those situations where everyone just says "It's not supported" but really just doesn't know. Does anyone have the official word or link to an SAP statement that this functionality is officially not supported.What I would say is, it won't support. The reason could be, as its not support any structure view in universe designer, that means we cannot create any derived tables where we could use sql query.
I believe the same applies here too. Even if you look at LOV defintions in universe, it won't show any query.
So the same applies to reports.
Hope this helps.
Regards
Gowtham -
SQL Query using Subquery to get the difference in budget versions
Hi
I am using the following query to find the difference between revenue budget changes from the previous version to latest version. However the second subquery is not working. Has somebody done a similar query before? Any help?
select distinct b.name, b.segment1, a.version_number , a.version_name, a.change_reason_code, a.revenue, f.revenue, a.creation_date, d.full_name
from PA_BUDGET_VERSIONS a, pa_projects_all b, fnd_user c, per_all_people_f d,PA_BUDGET_VERSIONS f
where a.project_id = b.project_id
and a.created_by = c.user_id
and c.employee_id = d.person_id
and a.budget_type_code = 'AR'
and a.budget_status_code = 'B'
and b.org_id in (147,707,140)
and a.version_number in (select max(e.version_number) from PA_BUDGET_VERSIONS e where e.budget_version_id = a.budget_version_id
and a.project_id = e.project_id)
and a.budget_version_id = f.budget_version_id
and f.version_number in (Select max(g.version_number) from PA_BUDGET_VERSIONS g where f.budget_version_id = g.budget_version_id
and f.project_id = g.project_id and g.version_number < a.version_number)
and a.creation_date between '01-JAN-09' and '30-JAN-09'
order by b.segment1;Analytic functions to the rescue! (Now you'll only have one pass through the pa_budget_version table, instead of four!)
Something like this, perhaps (assuming version_numbers are unique per project_id and budget_version_id):
WITH a AS (SELECT project_id,
version_number,
version_name,
change_reason_code,
creation_date,
revenue,
row_number() over (partition by project_id, budget_version_id
order by version_number desc) rn,
lag(revenue) over (partition by project_id, budget_version_id
order by version_number desc) prev_ver_revenue
FROM pa_budget_versions
WHERE budget_type_code = 'AR'
AND budget_status_code = 'B'
AND creation_date BETWEEN to_date('01/01/2009', 'dd/mm/yyyy')
AND to_date('30/01/2009', 'dd/mm/yyyy'))
SELECT DISTINCT b.name,
b.segment1,
a.version_number,
a.version_name,
a.change_reason_code,
a.revenue,
a.prev_ver_revenue,
a.creation_date,
d.full_name
FROM a,
pa_projects_all b,
fnd_user c,
per_all_people_f d
WHERE a.project_id = b.project_id
AND a.created_by = c.user_id
AND c.employee_id = d.person_id
AND b.org_id IN (147, 707, 140)
ORDER BY b.segment1;NB. untested. -
Using all results in a multiple row resultset returned by a subquery
I solved the problem of splitting up the dimension fields for each account code as referenced in my first post. Now I am needing to return the budget amounts of each account code (some account codes return multiple amounts). I need to do this
for five sets of years so that I show each year in its own column (a Proposed Budget Year, a Current Budget Year, and three historical budget years).
Right now I am attempting to use joins to the three tables that show the different types of amounts. Some account codes will return multiple amount values for the same account code in the same year. I need all of these amounts in a row associated
with the account code so that I can group and sum them later on by differing criteria from the dimension fields. Here is what I have so far (it returns the account codes and dimension fields correctly, but the amounts aren't working and I can't figure
out how to make them work.
USE [Financial]
-- Input variables from web page
DECLARE @pkYear INT;
DECLARE @Fund INT;
DECLARE @Function INT;
DECLARE @FundingSource INT;
DECLARE @OperationalUnit INT;
DECLARE @JobClass INT;
DECLARE @Version INT;
DECLARE @Object INT;
DECLARE @Instorg INT;
DECLARE @SubMat INT;
DECLARE @SCC INT;
DECLARE @ExcludeNoAct INT;
DECLARE @CurrentUser INT;
-- Variables to calculate budget years
DECLARE @PeriodStartDate VARCHAR(256);
DECLARE @PeriodEndDate VARCHAR(256);
DECLARE @ProposedBudgetYear INT;
DECLARE @CurrentBudgetYear INT;
DECLARE @BudgetYear1 INT;
DECLARE @BudgetYear2 INT;
DECLARE @BudgetYear3 INT;
DECLARE @YearStartDateYear INT;
DECLARE @ProposedYearStartDateYear INT;
DECLARE @Year1StartDateYear INT;
DECLARE @Year2StartDateYear INT;
DECLARE @Year3StartDateYear INT;
DECLARE @YearStartDate DATE;
-- Set variables to test query
SET @pkYear = 5;
SET @ExcludeNoAct = 0;
SET @CurrentUser = 1;
SET @YearStartDate = (SELECT TOP 1 BeginDate FROM fiYear Y
Where Y.pkYear = @pkYear);
PRINT @pkYear;
PRINT @YearStartDate;
-- Set variables for budget years
SET @YearStartDateYear = YEAR(@YearStartDate);
SET @ProposedYearStartDateYear = @YearStartDateYear + 1;
SET @Year1StartDateYear = @YearStartDateYear - 1;
SET @Year2StartDateYear = @YearStartDateYear - 2;
SET @Year3StartDateYear = @YearStartDateYear - 3;
PRINT @YearStartDateYear;
PRINT @ProposedYearStartDateYear;
PRINT @Year1StartDateYear;
PRINT @Year2StartDateYear;
PRINT @Year3StartDateYear;
-- Set budget years based on year input parameter
SET @ProposedBudgetYear = (SELECT pkYear
FROM fiYear
WHERE YEAR(fiYear.BeginDate) = @ProposedYearStartDateYear)
SET @CurrentBudgetYear = (SELECT pkYear
FROM fiYear
WHERE YEAR(fiYear.BeginDate) = @YearStartDateYear)
SET @BudgetYear1 = (SELECT pkYear
FROM fiYear
WHERE YEAR(fiYear.BeginDate) = @Year1StartDateYear)
SET @BudgetYear2 = (SELECT pkYear
FROM fiYear
WHERE YEAR(fiYear.BeginDate) = @Year2StartDateYear)
SET @BudgetYear3 = (SELECT pkYear
FROM fiYear
WHERE YEAR(fiYear.BeginDate) = @Year3StartDateYear)
PRINT @ProposedBudgetYear;
PRINT @CurrentBudgetYear;
PRINT @BudgetYear1;
PRINT @BudgetYear2;
PRINT @BudgetYear3;
-- Query building exercise
DECLARE @fkState INT
DECLARE @fkDimPosFund INT
DECLARE @fkDimPosFunction INT
DECLARE @fkDimPosObject INT
DECLARE @fkDimPosFundingSource INT
DECLARE @fkDimPosInstructionalOrganization INT
DECLARE @fkDimPosOperationalUnit INT
DECLARE @fkDimPosSubjectMatter INT
DECLARE @fkDimPosJobClass INT
DECLARE @fkDimPosSpeclCostCntr INT
SET @fkState = 40
SET @Version = 11
--Get the position of the fund account code dimensions determined by state
SELECT @fkDimPosFund = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'FUND' AND @fkState = fiDimensionPosition.fkState
SELECT @fkDimPosFunction = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'FUNCTION' AND @fkState = fiDimensionPosition.fkState
SELECT @fkDimPosObject = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'OBJECT' AND @fkState = fiDimensionPosition.fkState
SELECT @fkDimPosFundingSource = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'FUNDING SOURCE' AND @fkState = fiDimensionPosition.fkState
SELECT @fkDimPosInstructionalOrganization = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'INSTRUCTIONAL ORGANIZATION' AND @fkState = fiDimensionPosition.fkState
SELECT @fkDimPosOperationalUnit = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'OPERATIONAL UNIT' AND @fkState = fiDimensionPosition.fkState
SELECT @fkDimPosSubjectMatter = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'SUBJECT MATTER' AND @fkState = fiDimensionPosition.fkState
SELECT @fkDimPosJobClass = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'JOB CLASS' AND @fkState = fiDimensionPosition.fkState
SELECT @fkDimPosSpeclCostCntr = pkDimensionPosition FROM fiDimensionPosition WHERE Title = 'SPECIAL COST CENTER' AND @fkState = fiDimensionPosition.fkState
PRINT @fkDimPosFund
PRINT @fkDimPosFunction
PRINT @fkDimPosObject
PRINT @fkDimPosFundingSource
PRINT @fkDimPosInstructionalOrganization
PRINT @fkDimPosOperationalUnit
PRINT @fkDimPosSubjectMatter
PRINT @fkDimPosJobClass
PRINT @fkDimPosSpeclCostCntr
SELECT ACCTCODE.fkYear
,Y.YearID
,ACCTCODE.AccountCode
,DIMFUND.Dimension AS [Fund]
,DIMFUNCTION.Dimension AS [Function]
,DIMOBJECT.Dimension AS [Object]
,(SELECT LEFT ( DIMOBJECT.Dimension , 1 )) AS [MAJOR OBJECT]
,DIMFUNDINGSOURCE.Dimension AS [Funding Source]
,DIMFUNDINGINSTRUCTIONALORG.Dimension AS [Instructional Organization]
,DIMOPUNIT.Dimension AS [Operational Unit]
,DIMSUBMATTER.Dimension AS [Subject Matter]
,DIMJOBCLASS.Dimension AS [Job Classification]
,DIMSPECLCOSTCNTR.Dimension AS [Special Cost Center]
,BP.Amount AS Proposed
,B.Amount AS [Current]
,T1.Amount AS [Historical]
FROM fiAccountCode ACCTCODE
JOIN fiDimension DIMFUND
ON DIMFUND.fkDimensionPosition = @fkDimPosFund
AND (DIMFUND.pkDimension = ACCTCODE.fkDimension1
OR DIMFUND.pkDimension = ACCTCODE.fkDimension2
OR DIMFUND.pkDimension = ACCTCODE.fkDimension3
OR DIMFUND.pkDimension = ACCTCODE.fkDimension4
OR DIMFUND.pkDimension = ACCTCODE.fkDimension5
OR DIMFUND.pkDimension = ACCTCODE.fkDimension6
OR DIMFUND.pkDimension = ACCTCODE.fkDimension7
OR DIMFUND.pkDimension = ACCTCODE.fkDimension8
OR DIMFUND.pkDimension = ACCTCODE.fkDimension9
JOIN fiDimension DIMFUNCTION
ON DIMFUNCTION.fkDimensionPosition = @fkDimPosFund
AND (DIMFUNCTION.pkDimension = ACCTCODE.fkDimension1
OR DIMFUNCTION.pkDimension = ACCTCODE.fkDimension2
OR DIMFUNCTION.pkDimension = ACCTCODE.fkDimension3
OR DIMFUNCTION.pkDimension = ACCTCODE.fkDimension4
OR DIMFUNCTION.pkDimension = ACCTCODE.fkDimension5
OR DIMFUNCTION.pkDimension = ACCTCODE.fkDimension6
OR DIMFUNCTION.pkDimension = ACCTCODE.fkDimension7
OR DIMFUNCTION.pkDimension = ACCTCODE.fkDimension8
OR DIMFUNCTION.pkDimension = ACCTCODE.fkDimension9
JOIN fiDimension DIMOBJECT
ON DIMOBJECT.fkDimensionPosition = @fkDimPosFund
AND (DIMOBJECT.pkDimension = ACCTCODE.fkDimension1
OR DIMOBJECT.pkDimension = ACCTCODE.fkDimension2
OR DIMOBJECT.pkDimension = ACCTCODE.fkDimension3
OR DIMOBJECT.pkDimension = ACCTCODE.fkDimension4
OR DIMOBJECT.pkDimension = ACCTCODE.fkDimension5
OR DIMOBJECT.pkDimension = ACCTCODE.fkDimension6
OR DIMOBJECT.pkDimension = ACCTCODE.fkDimension7
OR DIMOBJECT.pkDimension = ACCTCODE.fkDimension8
OR DIMOBJECT.pkDimension = ACCTCODE.fkDimension9
JOIN fiDimension DIMFUNDINGSOURCE
ON DIMFUNDINGSOURCE.fkDimensionPosition = @fkDimPosFund
AND (DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension1
OR DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension2
OR DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension3
OR DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension4
OR DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension5
OR DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension6
OR DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension7
OR DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension8
OR DIMFUNDINGSOURCE.pkDimension = ACCTCODE.fkDimension9
JOIN fiDimension DIMFUNDINGINSTRUCTIONALORG
ON DIMFUNDINGINSTRUCTIONALORG.fkDimensionPosition = @fkDimPosFund
AND (DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension1
OR DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension2
OR DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension3
OR DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension4
OR DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension5
OR DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension6
OR DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension7
OR DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension8
OR DIMFUNDINGINSTRUCTIONALORG.pkDimension = ACCTCODE.fkDimension9
JOIN fiDimension DIMOPUNIT
ON DIMOPUNIT.fkDimensionPosition = @fkDimPosFund
AND (DIMOPUNIT.pkDimension = ACCTCODE.fkDimension1
OR DIMOPUNIT.pkDimension = ACCTCODE.fkDimension2
OR DIMOPUNIT.pkDimension = ACCTCODE.fkDimension3
OR DIMOPUNIT.pkDimension = ACCTCODE.fkDimension4
OR DIMOPUNIT.pkDimension = ACCTCODE.fkDimension5
OR DIMOPUNIT.pkDimension = ACCTCODE.fkDimension6
OR DIMOPUNIT.pkDimension = ACCTCODE.fkDimension7
OR DIMOPUNIT.pkDimension = ACCTCODE.fkDimension8
OR DIMOPUNIT.pkDimension = ACCTCODE.fkDimension9
JOIN fiDimension DIMSUBMATTER
ON DIMSUBMATTER.fkDimensionPosition = @fkDimPosFund
AND (DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension1
OR DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension2
OR DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension3
OR DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension4
OR DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension5
OR DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension6
OR DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension7
OR DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension8
OR DIMSUBMATTER.pkDimension = ACCTCODE.fkDimension9
JOIN fiDimension DIMJOBCLASS
ON DIMJOBCLASS.fkDimensionPosition = @fkDimPosFund
AND (DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension1
OR DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension2
OR DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension3
OR DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension4
OR DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension5
OR DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension6
OR DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension7
OR DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension8
OR DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension9
JOIN fiDimension DIMSPECLCOSTCNTR
ON DIMJOBCLASS.fkDimensionPosition = @fkDimPosFund
AND (DIMJOBCLASS.pkDimension = ACCTCODE.fkDimension1
OR DIMSPECLCOSTCNTR.pkDimension = ACCTCODE.fkDimension2
OR DIMSPECLCOSTCNTR.pkDimension = ACCTCODE.fkDimension3
OR DIMSPECLCOSTCNTR.pkDimension = ACCTCODE.fkDimension4
OR DIMSPECLCOSTCNTR.pkDimension = ACCTCODE.fkDimension5
OR DIMSPECLCOSTCNTR.pkDimension = ACCTCODE.fkDimension6
OR DIMSPECLCOSTCNTR.pkDimension = ACCTCODE.fkDimension7
OR DIMSPECLCOSTCNTR.pkDimension = ACCTCODE.fkDimension8
OR DIMSPECLCOSTCNTR.pkDimension = ACCTCODE.fkDimension9
JOIN faBudgetPrep BP ON ACCTCODE.pkAccountCode = BP.fkAccountCode
JOIN fiBudget B ON B.fkAccountCode = ACCTCODE.pkAccountCode
JOIN faTransaction T1 ON T1.fkAccountCode = ACCTCODE.pkAccountCode
JOIN fiYear Y ON Y.pkYear = ACCTCODE.fkYear
ORDER BY Y.YearID
If I run the query without the amounts included, I get all the account codes and dimension fields fine. If I try to include the amounts I get an empty result set. I tried using a subquery to get the amounts, but it erred out due to returning multiple
results for each account code on a given amount type in a given year. I'm stuck. Please help.
RandyHJ1957The amounts are coming from three other tables that are not yet included in the existing query. Depending on the year being referenced, the amounts come from the following tables:
ProposedBudget amounts come from the BudgetPrep table (BudgetPrep.Amount).
CurrentBudget amounts come from the Budget table (Budget.Amount)
Each of the the historical years of budget amounts come from the Transactions table, which I call three times with different table aliases (T1, T2, T3) so that I use the following columns T1.Amount, T2.Amount, and T3.Amount for each respective historical
year.
For example, I want my years to appear as columns in the result set:
ProposedBudget Current Budget Historical 1 Historical 2 Historical 3
2015 2014 2013 2012
2011
I need to join the amounts to the account codes for each year I am dealing with.
Sometimes there are several results for the amount per account code in a year (representing different fund divisions) and I need to display all the amounts so I can group and sum them later in a report. I'm trying to gather all the amounts for each
account code (and its respective line items) for each of the five years so I can present the data in a report.
RandyHJ1957
Maybe you are looking for
-
A query about SOA Design and development
Hi Why everybody these days are interested in SOA ?? The question i mean to ask is from a Service User Perspective , arent we coding our Application forcefully in the idea of making use of Other Software ?? Isn't this is a draw back ? (I am asking in
-
Intercom Zones or groups in Call Manager Express
In CME 9.1 How do you set up the SCCP to SCCP phone Intercom feature to call a group of phones or zones?
-
SP2-0310 trying to upgrade PL/SQL Web Toolkit on 10g XE
Hi, I upgraded my local Oracle 10g XE APEX installation to version 4.0.2.00.06 but then I realized that I probably also needed a newer version of the PL/SQL Web Toolkit. So I changed my path to the owa folder and then I executed owainst.sql connected
-
Safari is constantly crashing.Ver 5.05
This is the report I keep getting. " Process: Safari [657] Path: /Applications/Safari.app/Contents/MacOS/Safari Identifier: com.apple.Safari Version: 5.0.5 (6533.21.1) Build Info: WebBrowser-75332101~1 Code Type:
-
The top of the pdf says it can be Saved As. However when I go to save the PDF I get a message that says only a blank version will be saved. I call the company that I got the PDF from and they were able to save on their computer, but it won't save on