SQL query with multiple condition
Below is the sample table
ID RATE DATE ORGAMNT PAYAMOUNT
1 3.45 12/23/2012 23000.45 19060.23
2. 5.50 04/12/2013 45000.00 36000.54
3. 6.44 04/16/200 60000.00 20000.00
Select a table with highest rate, Orgamnt with Date closer to current date.
with
data_table as
(select 11186 hnum,11607400 oma,to_date('2/1/2006','mm/dd/yyyy') fpay,5.51 irate,10580934.67 apb,'WELLS FARGO BANK NA' hname from dual union all
select 11188,4801800,to_date('9/1/2006','mm/dd/yyyy'),6.3,4326951.51,'PNC BANK, NATIONAL ASSOCIATION' hname from dual union all
select 11189,1236100,to_date('8/1/2006','mm/dd/yyyy'),6.15,1147108.9,'HEARTLAND BANK' hname from dual union all
select 11192,1578400,to_date('4/1/2007','mm/dd/yyyy'),5.82,1470926.86,'WELLS FARGO BANK NA' hname from dual union all
select 11193,8150400,to_date('12/1/2008','mm/dd/yyyy'),6.75,7828776.28,'OPPENHEIMER MULTIFAMILY HSG' hname from dual union all
select 11195,3898000,to_date('5/1/2009','mm/dd/yyyy'),6.5,3752154.96,'BERKADIA COMMERCIAL MORTGAGE' hname from dual union all
select 11196,8040000,to_date('6/1/2009','mm/dd/yyyy'),7,7775734.57,'OPPENHEIMER MULTIFAMILY HSG' hname from dual union all
select 11197,37315000,to_date('12/1/2009','mm/dd/yyyy'),5.5,35851362.87,'RED MORTGAGE CAPITAL LLC' hname from dual union all
select 11199,3824000,to_date('2/1/2010','mm/dd/yyyy'),5.25,3673760.35,'WALKER AND DUNLOP LLC' hname from dual union all
select 11200,26927000,to_date('7/1/2010','mm/dd/yyyy'),4.7,25186682.65,'OAK GROVE COMMERCIAL MORTGAGE' hname from dual union all
select 11201,7208600,to_date('10/1/2010','mm/dd/yyyy'),4.59,6949026.64,'BERKADIA COMMERCIAL MORTGAGE' hname from dual union all
select 11204,9300000,to_date('2/1/2011','mm/dd/yyyy'),3.41,8927064.51,'PNC BANK, NATIONAL ASSOCIATION' hname from dual union all
select 11205,5200000,to_date('2/1/2011','mm/dd/yyyy'),3.56,4997518.18,'LOVE FUNDING CORPORATION' hname from dual union all
select 11206,6800000,to_date('5/1/2011','mm/dd/yyyy'),3.88,6576635.57,'WELLS FARGO BANK NA' hname from dual union all
select 11208,12240000,to_date('8/1/2011','mm/dd/yyyy'),3.84,11879882.17,'WELLS FARGO BANK NA' hname from dual union all
select 11209,12911500,to_date('10/1/2011','mm/dd/yyyy'),3.55,12542199.51,'M AND T REALTY CAPITAL CORP' hname from dual union all
select 11210,9596900,to_date('7/1/2011','mm/dd/yyyy'),5.38,9323421.23,'LANCASTER POLLARD MORTGAGE' hname from dual union all
select 11211,19951600,to_date('9/1/2011','mm/dd/yyyy'),3.88,19393524.45,'DEUTSCHE BANK BERKSHIRE MORTGAGE' hname from dual union all
select 11183,4230000,to_date('4/1/2009','mm/dd/yyyy'),6.55,4069938.75,'BERKADIA COMMERCIAL MORTGAGE' hname from dual union all
select 11212,50475000,to_date('1/1/2013','mm/dd/yyyy'),2.37,49852632.51,'LOVE FUNDING CORPORATION' hname from dual union all
select 11213,5496000,to_date('5/1/2012','mm/dd/yyyy'),3.1,5377541.15,'WELLS FARGO BANK NA' hname from dual
select hnum,oma,fpay,irate,apb,hname,r_oma,r_irate,r_fpay,0.5 * r_oma + 0.3 * r_irate + 0.2 * r_fpay r
from (select hnum,oma,fpay,irate,apb,hname,
dense_rank() over (order by oma desc) r_oma,
dense_rank() over (order by irate desc) r_irate,
dense_rank() over (order by (sysdate - fpay)) r_fpay
from data_table
order by r
HNUM
OMA
FPAY
IRATE
APB
HNAME
R_OMA
R_IRATE
R_FPAY
R
11197
37315000
12/01/2009
5.5
35851362.87
RED MORTGAGE CAPITAL LLC
2
9
12
6.1
11212
50475000
01/01/2013
2.37
49852632.51
LOVE FUNDING CORPORATION
1
20
1
6.7
11211
19951600
09/01/2011
3.88
19393524.45
DEUTSCHE BANK BERKSHIRE MORTGAGE
4
14
4
7
11200
26927000
07/01/2010
4.7
25186682.65
OAK GROVE COMMERCIAL MORTGAGE
3
12
10
7.1
11209
12911500
10/01/2011
3.55
12542199.51
M AND T REALTY CAPITAL CORP
5
17
3
8.2
11210
9596900
07/01/2011
5.38
9323421.23
LANCASTER POLLARD MORTGAGE
8
10
6
8.2
11196
8040000
06/01/2009
7
7775734.57
OPPENHEIMER MULTIFAMILY HSG
11
1
13
8.4
11208
12240000
08/01/2011
3.84
11879882.17
WELLS FARGO BANK NA
6
15
5
8.5
11193
8150400
12/01/2008
6.75
7828776.28
OPPENHEIMER MULTIFAMILY HSG
10
2
16
8.8
11186
11607400
02/01/2006
5.51
10580934.67
WELLS FARGO BANK NA
7
8
20
9.9
11204
9300000
02/01/2011
3.41
8927064.51
PNC BANK, NATIONAL ASSOCIATION
9
18
8
11.5
11201
7208600
10/01/2010
4.59
6949026.64
BERKADIA COMMERCIAL MORTGAGE
12
13
9
11.7
11206
6800000
05/01/2011
3.88
6576635.57
WELLS FARGO BANK NA
13
14
7
12.1
11183
4230000
04/01/2009
6.55
4069938.75
BERKADIA COMMERCIAL MORTGAGE
17
3
15
12.4
11195
3898000
05/01/2009
6.5
3752154.96
BERKADIA COMMERCIAL MORTGAGE
18
4
14
13
11188
4801800
09/01/2006
6.3
4326951.51
PNC BANK, NATIONAL ASSOCIATION
16
5
18
13.1
11213
5496000
05/01/2012
3.1
5377541.15
WELLS FARGO BANK NA
14
19
2
13.1
11205
5200000
02/01/2011
3.56
4997518.18
LOVE FUNDING CORPORATION
15
16
8
13.9
11199
3824000
02/01/2010
5.25
3673760.35
WALKER AND DUNLOP LLC
Similar Messages
-
Same sql query with multiple database links
Hi All,
i want to execute an sql query for a SELECT LIST Item. which should use database links in it's query.
i'm having a list of database links in the region. say :LOC which is having 10 items each linking to different databases.
i want to use following query for another item in same page.
select customer_name from working_lines@:LOC where
phone_no:phone_no
can i do this.
Thank you All.What we have done before is to create a report based on a PL/SQL procedure that returns a SQL statement.
The PL/SQL code grabs the "selected" database link from :LOC and parses the SQL QUERY you want to execute replacing some token (like [LINK]) with '@DBNAME'.
Lets say your SQL statement is coded like this:
mySQL := 'SELECT cust_name FROM working_lines[LINK] where phone_no = :Phone;'
Then all you would have to do to replace '[LINK]' with the proper DB alias would be:
mySQL := REPLACE(mySQL, '[LINK]', '@'||:LOC);
and then return the new SQL ...
if :LOC has something like 'V10GPROD' your SQL would look like :
SELECT cust_name FROM working_lines@V10GPROD where phone_no = :Phone;
The beauty of this is that you can also include a "null" option that means the select statement will be executed on THIS database...
Doug -
Sql query with multiple joins to same table
I have to write a query for a client to display business officers' names and title along with the business name
The table looks like this
AcctNumber
OfficerTitle
OfficerName
RecKey
90% of the businesses have exactly 4 officer records, although some have less and some have more.
There is a separate table that has the AcctNumber, BusinessName about 30 other fields that I don’t need
An individual account can have 30 or 40 records on the other table.
The client wants to display 1 record per account.
Initially I wrote a query to join the table to itself:
Select A.OfficerTtitle, A.OfficerName, B.OfficerTitle, B.OfficerName, C.OfficerTtitle, C.OfficerName, D.OfficerTitle, D.OfficerName where A.AcctNumber = B.AcctNumber and A.AcctNumber = C.AcctNumber and A.AcctNumber = D.AcctNumber
This returned tons of duplicate rows for each account ( number of records * number of records, I think)
So added
And A.RecKey > B.RecKey and B.RecKey > C. RecKey and C.RecKey . D.RecKey
This works when there are exactly 4 records per account. If there are less than 4 records on the account it skips the account and if there are more than 4 records, it returns multiple rows.
But when I try to l join this to the other table to get the business name, I get a row for every record on the other table
I tried select distinct on the other table and the query runs for ever and never returns anything
I tried outer joins and subqueries, but no luck so far. I was thinking maybe a subquery - if exists - because I don't know how many records there are on an account, but don't know how to structure that
Any suggestions would be appreciatedWelcome to the forum!
user13319842 wrote:
I have to write a query for a client to display business officers' names and title along with the business name
The table looks like this
AcctNumber
OfficerTitle
OfficerName
RecKey
90% of the businesses have exactly 4 officer records, although some have less and some have more.
There is a separate table that has the AcctNumber, BusinessName about 30 other fields that I don’t need
An individual account can have 30 or 40 records on the other table.
The client wants to display 1 record per account.As someone has already mentioned, you should post CREATE TABLE and INSERT statements for both tables (relevant columns only). You don't have to post a lot of sample data. For example, you need to pick 1 out of 30 or 40 rows (max) for the same account, but it's almost certainly enough if you post only 3 or 4 rows (max) for an account.
Also, post the results you want from the sample data that you post, and explain how you get those resutls from that data.
Always say which version of Oracle you're using. This sounds like a PIVOT problem, and a new SELECT .... PIVOT feature was introduced in Oracle 11.1. If you're using Oracle 11, you don't want to have to learn the old way to do pivots. On the other hand, if you have Oracle 10, a solution that uses a new feature that you don't have won't help you.
Whenever you have a question, please post CREATE TABLE and INSERT statements for some sample data, the results you want from that data, an explanation, and your Oracle version.
Initially I wrote a query to join the table to itself:
Select A.OfficerTtitle, A.OfficerName, B.OfficerTitle, B.OfficerName, C.OfficerTtitle, C.OfficerName, D.OfficerTitle, D.OfficerName where A.AcctNumber = B.AcctNumber and A.AcctNumber = C.AcctNumber and A.AcctNumber = D.AcctNumber Be careful, and post the exact code that you're running. The statement above can't be what you ran, because it doesn't have a FROM clause.
This returned tons of duplicate rows for each account ( number of records * number of records, I think)
So added
And A.RecKey > B.RecKey and B.RecKey > C. RecKey and C.RecKey . D.RecKey
This works when there are exactly 4 records per account. If there are less than 4 records on the account it skips the account and if there are more than 4 records, it returns multiple rows.
But when I try to l join this to the other table to get the business name, I get a row for every record on the other table
I tried select distinct on the other table and the query runs for ever and never returns anything
I tried outer joins and subqueries, but no luck so far. I was thinking maybe a subquery - if exists - because I don't know how many records there are on an account, but don't know how to structure that
Any suggestions would be appreciatedDisplaying 1 column from n rows as n columns on 1 row is called Pivoting . See the following link fro several ways to do pivots:
SQL and PL/SQL FAQ
Pivoting requires that you know exactly how many columns will be in the result set. If that number depends on the data in the table, then you might prefer to use String Aggregation , where the output consists of a huge string column, that contains the concatenation of the data from n rows. This big string can be formatted so that it looks like multiple columns. For different string aggregation techniques, see:
http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
The following thread discusses some options for pivoting a variable number of columns:
Re: Report count and sum from many rows into many columns -
SQL query with multiple tables - what is the most efficient way?
Hello I am learning PL/SQL. I have a simple procedure where I need to find number of employees and departments per location as per user input of location_id.
I have 3 Tables:
LOCATIONS
location_id (pk)
location_name
DEPARTMENTS
department_id (pk)
location_id (fk)
department_name
EMPLOYEES
employee_id (pk)
department_id (fk)
employee_name
1 Location can have 0-MANY Departments
1 Employee has 1 Department
Here is the query I came up with for PL/SQL procedure:
/*Ecount, Dcount are NUMBER variables */
SELECT SUM (EmployeeCount), COUNT(DepartmentNumber)
INTO Ecount, Dcount
FROM
(SELECT COUNT(employee_id) EmployeeCount, department_id DepartmentNumber
FROM employees
GROUP BY department_id
HAVING department_id IN
(SELECT department_id
FROM departments
WHERE location_id = userInput));
I do get the correct result, but I am just wondering if my query is on the right track and if there is a more "efficient" way of doing this.
Thanks in advance for helping a newbie out.Hi,
Welcome to the forum!
Something like this will be more efficient:
SELECT COUNT (employee_id) AS ECount
, COUNT (DISTINCT department_id) AS DCount
FROM employees
WHERE department_id IN ( SELECT department_id
FROM departments
WHERE location_id = :userInput
;You should also try a join instead of the IN subquery.
For efficiency, do only the things you need to do.
For example, you don't need a count of employees in each department, so don't compute one. That means you won't need the in-line view, so don't have one.
You don't need PL/SQL for this job, so don't use PL/SQL if you don't have to. (I realize this question was out of context, so you may have good reasons for doing this in PL/SQL.)
Do all filtering as early as possible. Don't waste effort computing things that won't be used .
A particular example of this is: Never use a HAVING clause when you can use a WHERE clause. What's the difference between a WHERE clause and a HAVING clause? The WHERE clause is applied before aggregate functions are computed, and the HAVING clause is applied after; there's no other difference. Therefore, if the HAVING clause isn't referencing an aggregate function, it could be done in a WHERE clause instead. -
Performance tuning of sql query with multiple joins
My query takes at least half an hour to execute and the number of records returned are approx 1 lakh records.
Structure of tables are:
tblSession : ID,option1,option2,option3,option4,option5,option6,option7,option8,option9.
tblOption : ID, labelID
tblLabelDetail : ID, LABELID, text
optionID 1 to optionID9 are Foreign keys to table tblOption.ID
My query is as below :
select
session.ID
,session.tstamp
,session.score
,session.hid1
,session.hID2
,session.hID3
,session.collectionID
,session.consumerID
,session.langID
,cons_cust.text1 as customCons_text1,
cons_cust.text2 as customCons_text2,
cons_cust.text3 as customCons_text3,
cons_cust.text4 as customCons_text4,
cons_cust.text5 as customCons_text5,
cons_cust.text6 as customCons_text6,
cons_cust.text7 as customCons_text7,
cons_cust.text8 as customCons_text8,
cons_cust.text9 as customCons_text9,
ld_cons1.text as customCons_option1GUID,
ld_cons2.text as customCons_option2GUID,
ld_cons3.text as customCons_option3GUID,
ld_cons4.text as customCons_option4GUID ,
ld_cons5.text as customCons_option5GUID,
ld_cons6.text as customCons_option6GUID,
ld_cons7.text as customCons_option7GUID,
ld_cons8.text as customCons_option8GUID,
ld_cons9.text as customCons_option9GUID,
--session
session_cust.text1 as session_cust_text1,
session_cust.text2 as session_cust_text2,
session_cust.text3 as session_cust_text3,
session_cust.text4 as session_cust_text4,
session_cust.text5 as session_cust_text5,
session_cust.text6 as session_cust_text6,
session_cust.text7 as session_cust_text7,
session_cust.text8 as session_cust_text8,
session_cust.text9 as session_cust_text9,
ld_sess1.text as session_cust_option1GUID,
ld_sess2.text as session_cust_option2GUID,
ld_sess3.text as session_cust_option3GUID,
ld_sess4.text as session_cust_option4GUID,
ld_sess5.text as session_cust_option5GUID,
ld_sess6.text as session_cust_option6GUID,
ld_sess7.text as session_cust_option7GUID,
ld_sess8.text as session_cust_option8GUID,
ld_sess9.text as session_cust_option9GUID,
session_cust.tStamp1,
session_cust.tStamp2
from mvSession session with (noexpand)
inner join tblCollection c on c.ID=session.collectionID AND c.templateID = 405
left join tblConsumer cons on cons.ID=session.consumerID and cons.sessionYM between 601 and 1412 and cons.sID=105
left join vCustomConsumer cons_cust on cons_cust.sessionYM between 601 and 1412 and cons_cust.sID=105 and cons_cust.ID=cons.ID
left join tbloption o_cons1 on o_cons1.id = cons_cust.option1 and o_cons1.sid = 105
left join tblLabelDetail ld_cons1 on ld_cons1.labelID = o_cons1.labelID and ld_cons1.langId = 1 and ld_cons1.eid = 107
left join tbloption o_cons2 on o_cons2.id = cons_cust.option2 and o_cons2.sid = 105
left join tblLabelDetail ld_cons2 on ld_cons2.labelID = o_cons2.labelID and ld_cons2.langId = 1 and ld_cons2.eid = 107
left join tbloption o_cons3 on o_cons3.id = cons_cust.option3 and o_cons3.sid = 105
left join tblLabelDetail ld_cons3 on ld_cons3.labelID = o_cons1.labelID and ld_cons3.langId = 1 and ld_cons3.eid = 107
left join tbloption o_cons4 on o_cons4.id = cons_cust.option4 and o_cons4.sid = 105
left join tblLabelDetail ld_cons4 on ld_cons4.labelID = o_cons4.labelID and ld_cons4.langId = 1 and ld_cons4.eid = 107
left join tbloption o_cons5 on o_cons5.id = cons_cust.option5 and o_cons5.sid = 105
left join tblLabelDetail ld_cons5 on ld_cons5.labelID = o_cons5.labelID and ld_cons5.langId = 1 and ld_cons5.eid = 107
left join tbloption o_cons6 on o_cons6.id = cons_cust.option6 and o_cons6.sid = 105
left join tblLabelDetail ld_cons6 on ld_cons6.labelID = o_cons6.labelID and ld_cons6.langId = 1 and ld_cons6.eid = 107
left join tbloption o_cons7 on o_cons7.id = cons_cust.option7 and o_cons7.sid = 105
left join tblLabelDetail ld_cons7 on ld_cons7.labelID = o_cons7.labelID and ld_cons7.langId = 1 and ld_cons7.eid = 107
left join tbloption o_cons8 on o_cons8.id = cons_cust.option8 and o_cons8.sid = 105
left join tblLabelDetail ld_cons8 on ld_cons8.labelID = o_cons8.labelID and ld_cons8.langId = 1 and ld_cons8.eid = 107
left join tbloption o_cons9 on o_cons9.id = cons_cust.option9 and o_cons9.sid = 105
left join tblLabelDetail ld_cons9 on ld_cons9.labelID = o_cons9.labelID and ld_cons9.langId = 1 and ld_cons9.eid = 107
left join vCustomSession session_cust on session_cust.sessionYM between 601 and 1412 and session_cust.sID=105 and session_cust.ID=session.ID
left join tbloption o_sess1 on o_sess1.id = session_cust.option1 and o_sess1.sid = 105
left join tblLabelDetail ld_sess1 on ld_sess1.labelID = o_sess1.labelID and ld_sess1.langId = 1 and ld_sess1.eid = 107
left join tbloption o_sess2 on o_sess2.id = session_cust.option2 and o_sess2.sid = 105
left join tblLabelDetail ld_sess2 on ld_sess2.labelID = o_sess2.labelID and ld_sess2.langId = 1 and ld_sess2.eid = 107
left join tbloption o_sess3 on o_sess2.id = session_cust.option3 and o_sess3.sid = 105
left join tblLabelDetail ld_sess3 on ld_sess3.labelID = o_sess2.labelID and ld_sess3.langId = 1 and ld_sess3.eid = 107
left join tbloption o_sess4 on o_sess4.id = session_cust.option4 and o_sess4.sid = 105
left join tblLabelDetail ld_sess4 on ld_sess4.labelID = o_sess4.labelID and ld_sess4.langId = 1 and ld_sess4.eid = 107
left join tbloption o_sess5 on o_sess5.id = session_cust.option5 and o_sess5.sid = 105
left join tblLabelDetail ld_sess5 on ld_sess5.labelID = o_sess5.labelID and ld_sess5.langId = 1 and ld_sess5.eid = 107
left join tbloption o_sess6 on o_sess6.id = session_cust.option6 and o_sess6.sid = 105
left join tblLabelDetail ld_sess6 on ld_sess6.labelID = o_sess6.labelID and ld_sess6.langId = 1 and ld_sess6.eid = 107
left join tbloption o_sess7 on o_sess7.id = session_cust.option7 and o_sess7.sid = 105
left join tblLabelDetail ld_sess7 on ld_sess7.labelID = o_sess7.labelID and ld_sess7.langId = 1 and ld_sess7.eid = 107
left join tbloption o_sess8 on o_sess8.id = session_cust.option8 and o_sess8.sid = 105
left join tblLabelDetail ld_sess8 on ld_sess8.labelID = o_sess8.labelID and ld_sess8.langId = 1 and ld_sess8.eid = 107
left join tbloption o_sess9 on o_sess9.id = session_cust.option9 and o_sess9.sid = 105
left join tblLabelDetail ld_sess9 on ld_sess9.labelID = o_sess9.labelID and ld_sess9.langId = 1 and ld_sess9.eid = 107
where session.sID=105 and session.tStamp >= 'Sep 1 2014 12:00AM' and session.tStamp < 'Dec 12 2014 12:00AM'
order by session.tStamp, session.ID
Is there a way , where i can simplify the joins with tbloption and tblLabelDetail and get my o/p in optimal time.
RegardsI have headed towards another approach ie. using unpivot and then pivot.
First i am converting option1-option9 into column , then doing PIVOT to get back the same record . But issue is that when i am doing pivoting i am getting NULL values.
My query is :
select * into #t1 from
select ID
, option1
, option2
, option3
, option4
, option5
, option6
, option7
, option8
, option9
from vCustomConsumer
where sid=105
and sessionYM = 1412
) SourceTable
UNPIVOT
optionID FOR Col IN
(option1
,option2
,option3
,option4
,option5
,option6
,option7
,option8
,option9 )
) AS unpvt
select t.ID,t.optionID,t.col,cast(ld.text as varchar(max)) as text into #t2
from #t1 t
left outer join tbloption o on o.ID = t.optionID
left outer join tblLabelDetail ld on ld.labelID = o.labelID and ld.langID=1
order by ID,col
select ID,option1
,option2
,[option3]
,option4
,option5
,option6
,option7
,option8
,option9
from
select ID,optionID,col,text
from #t2
)up
pivot
min(text)for col in
(option1
,option2
,[option3]
,option4
,option5
,option6
,option7
,option8
,option9
)as pvt
In my last query where i am using pivot, i am getting NULL values. When i check the data in temp table #t2 , it exists perfectly . But when pivoting i dont understand why it is returning most of the NULL values. I am getting data for only one column in single
row.
Below are some rows from result set finally obtained after pivoting :
ID
option1
option2
option3
option4
option5
option6
option7
option8
option9
62949026
NULL
0 to 200 seconds
NULL
NULL
NULL
NULL
NULL
NULL
NULL
62966000
NULL
NULL
4
NULL
NULL
NULL
NULL
NULL
NULL
62966032
NULL
NULL
4
NULL
NULL
NULL
NULL
NULL
NULL
63090372
NULL
NULL
NULL
NULL
EN
NULL
NULL
NULL
NULL
63090375
NULL
NULL
NULL
NULL
EN
NULL
NULL
NULL
NULL
Thanks, -
BaseTableName blank when calling GetSchema on a query with multiple tables
I am using ODP.NET 11.2.0.3.0 and when calling GetSchemaTable on a DataReader that contains a join the returned SchemaTable has the BaseTableName and BaseColumnName fields blank - this is different than what I see with the Oracle OLE DB Provider and with how SQL Server's native provider works. I can't find any discussion of this - is this on purpose or is it a bug? why does the available schema information vary so drastically between a single table query and a query with multiple tables joined?
Thanks,
Bryan HintonHi Bryan,
I am also facing the same issue. Did u find any work around or any suggestions will be well appreciated.
Thanks,
Naresh. -
Need help with SQL Query with Inline View + Group by
Hello Gurus,
I would really appreciate your time and effort regarding this query. I have the following data set.
Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
Please Ignore '----', added it for clarity
I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
The query should return the following data set
Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
The following is my query. I am kind of lost.
select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
from (
select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
from INVOICE
group by sequence_id,check_date, check_number, invoice_number, vendor_number
) A, INVOICE B
where A.sequence_id = B.sequence_id
Thanks,
NickIt looks like it is a duplicate thread - correct me if i'm wrong in this case ->
Need help with SQL Query with Inline View + Group by
Regards.
Satyaki De. -
Outer Joins with multiple conditions - alternatives to UNION?
It is my understanding that Oracle 8i does not directly support mutiple conditions for outer joins. For instance, I'm looking for PEOPLE who may, or may not, be on MEDICATIONS.
All MEDICATIONS are listed with DRUGNAME and DRUGID. There thousand of different drugs. I'm only looking for PEOPLE on either one or two of them (to make it simple) or no drug at all (ignoring all other DRUGS they're on..) IF they are on the DRUG, it's gerts printed.
I'd ideally do a LEFT OUTER JOIN to do this with multiple conditions:
SELECT DISTINCT
PERSON.NAME,
MEDICATION.DRUGNAME,
MEDICATION.DRUGID
FROM
PERSON,
MEDICATION
WHERE
PERSON.ID = MEDICATION.ID (+) AND
(MEDICATION.DRUGID (+) = 632 OR
MEDICATION.DRUGID (+) = 956)
This, of course, is not valid, at least in 8i...
So I've taken the UNION approach:
SELECT DISTINCT
PERSON.NAME,
MEDICATION.DRUGNAME,
MEDICATION.DRUGID
FROM
PERSON,
MEDICATION
WHERE
PERSON.ID = MEDICATION.ID (+) AND
MEDICATION.DRUGID (+) = 632
UNION
SELECT DISTINCT
PERSON.NAME,
MEDICATION.DRUGNAME,
MEDICATION.DRUGID
FROM
PERSON,
MEDICATION
WHERE
PERSON.ID = MEDICATION.ID (+) AND
MEDICATION.DRUGID (+) = 956
This of course, does work, but as I've added more drugs this becomes quite unwieldly and not really sure what this does to performance. (There are also several more joins to other tables, not relevent here.)
In addition, if I import this into Crystal Reports 8.5 (as opposed to the Crystal Query Designer), it refuses to recognize the UNION.
-- Any suggestions for alternative syntax ???
-- Has this been addressed in 9i ???
Thanks,
WillYou could try
select Distinct Person.Name, Med.DrugName, Med.DrugId
from Person,
(select ID, DrugName, DrugId from Medication
where DrugId in (632, 956) ) Med
where Person.ID = Med.ID(+)
SELECT DISTINCT
PERSON.NAME,
MEDICATION.DRUGNAME,
MEDICATION.DRUGID
FROM
PERSON,
MEDICATION
WHERE
PERSON.ID = MEDICATION.ID (+) AND
(MEDICATION.DRUGID (+) = 632 OR
MEDICATION.DRUGID (+) = 956)
This, of course, is not valid, at least in 8i...
So I've taken the UNION approach:
SELECT DISTINCT
PERSON.NAME,
MEDICATION.DRUGNAME,
MEDICATION.DRUGID
FROM
PERSON,
MEDICATION
WHERE
PERSON.ID = MEDICATION.ID (+) AND
MEDICATION.DRUGID (+) = 632
UNION
SELECT DISTINCT
PERSON.NAME,
MEDICATION.DRUGNAME,
MEDICATION.DRUGID
FROM
PERSON,
MEDICATION
WHERE
PERSON.ID = MEDICATION.ID (+) AND
MEDICATION.DRUGID (+) = 956
This of course, does work, but as I've added more drugs this becomes quite unwieldly and not really sure what this does to performance. (There are also several more joins to other tables, not relevent here.)
In addition, if I import this into Crystal Reports 8.5 (as opposed to the Crystal Query Designer), it refuses to recognize the UNION.
-- Any suggestions for alternative syntax ???
-- Has this been addressed in 9i ???
Thanks,
Will -
Extract Sql Query with Actual Parameters from Report
Hi
I am able to extract query from Crystal Report using the following code :
ReportDocument.ReportClientDocument.RowSetController.GetSqlStatement(new GroupPath, out tmp);
But the sql query retrieve comes in the following format :
select name , trans_code, account_code from command_query.accounts
where account_code = {?Command_query_Prompt0} and effective_date < '{?Command_query_prompt1 }'
The parameters which I m using in the reports are :
Account_Code and Effective_Date .
Why does my extracted sql translates it into {?Command_query_Prompt0} and '{?Command_query_prompt1 }' .
Is there any way to map this to the actual parameter values ?
OR
Can we extract the query after assigning the values ?
Any help is appreciated ...
Thanks
Sanchethi,
You can create nested sql query with conditional parameters,
For example
Select Code From OITT Where Code IN (Select ItemCode From OITM
Where ItemName LIKE '[%0]' + '%%')
Edited by: Jeyakanthan A on Jun 9, 2009 12:31 PM -
SQL query with Bind variable with slower execution plan
I have a 'normal' sql select-insert statement (not using bind variable) and it yields the following execution plan:-
Execution Plan
0 INSERT STATEMENT Optimizer=CHOOSE (Cost=7 Card=1 Bytes=148)
1 0 HASH JOIN (Cost=7 Card=1 Bytes=148)
2 1 TABLE ACCESS (BY INDEX ROWID) OF 'TABLEA' (Cost=4 Card=1 Bytes=100)
3 2 INDEX (RANGE SCAN) OF 'TABLEA_IDX_2' (NON-UNIQUE) (Cost=3 Card=1)
4 1 INDEX (FAST FULL SCAN) OF 'TABLEB_IDX_003' (NON-UNIQUE)
(Cost=2 Card=135 Bytes=6480)
Statistics
0 recursive calls
18 db block gets
15558 consistent gets
47 physical reads
9896 redo size
423 bytes sent via SQL*Net to client
1095 bytes received via SQL*Net from client
3 SQL*Net roundtrips to/from client
1 sorts (memory)
0 sorts (disk)
55 rows processed
I have the same query but instead running using bind variable (I test it with both oracle form and SQL*plus), it takes considerably longer with a different execution plan:-
Execution Plan
0 INSERT STATEMENT Optimizer=CHOOSE (Cost=407 Card=1 Bytes=148)
1 0 TABLE ACCESS (BY INDEX ROWID) OF 'TABLEA' (Cost=3 Card=1 Bytes=100)
2 1 NESTED LOOPS (Cost=407 Card=1 Bytes=148)
3 2 INDEX (FAST FULL SCAN) OF TABLEB_IDX_003' (NON-UNIQUE) (Cost=2 Card=135 Bytes=6480)
4 2 INDEX (RANGE SCAN) OF 'TABLEA_IDX_2' (NON-UNIQUE) (Cost=2 Card=1)
Statistics
0 recursive calls
12 db block gets
3003199 consistent gets
54 physical reads
9448 redo size
423 bytes sent via SQL*Net to client
1258 bytes received via SQL*Net from client
3 SQL*Net roundtrips to/from client
1 sorts (memory)
0 sorts (disk)
55 rows processed
TABLEA has around 3million record while TABLEB has 300 records. Is there anyway I can improve the speed of the sql query with bind variable? I have DBA Access to the database
Regards
IvanMany thanks for your reply.
I have run the statistic already for the both tableA and tableB as well all the indexes associated with both table (using dbms_stats, I am on 9i db ) but not the indexed columns.
for table I use:-
begin
dbms_stats.gather_table_stats(ownname=> 'IVAN', tabname=> 'TABLEA', partname=> NULL);
end;
for index I use:-
begin
dbms_stats.gather_index_stats(ownname=> 'IVAN', indname=> 'TABLEB_IDX_003', partname=> NULL);
end;
Is it possible to show me a sample of how to collect statisc for INDEX columns stats?
regards
Ivan -
SQL query with JSP and WML-parameters
Hey,
Could you help me?
I'm trying to do the following. WML deck card 1 send parameter to same WML deck's card help. I try to read the parameter with JSP in card help by putting the parameter to SQL query, but it doesn't work. I can read the parameter with WML in card help. I can also print the value of the parameter with JSP if I generate WML with JSP.
/*parameter sending from card 1 to card help*/
out.println("<go href='#helpcard'>");
out.println("<setvar name='valittukurssi' value='$(valittukurssi)'/>");
/*parameter read with WML in card help */
<p>Valitse kurssi.
$valittukurssi</p>
/'parameter read with JSP by generating WML with JSP*/
out.println("<p>$valittukurssi</p>");
/* SQL query with JSP */
ResultSet uudettulokset = uusilause.executeQuery("select * from kurssi where lyhenne='$valittukurssi'");
Thanks,
RampeYou're problem is easy to fix. You're confusing WML variables with JSP variables. See below:
>
/*parameter sending from card 1 to card help*/
out.println("<go href='#helpcard'>");
out.println("<setvar name='valittukurssi'
value='$(valittukurssi)'/>");
Above you set a var that will work on the phone, not in JSP.
/*parameter read with WML in card help */
<p>Valitse kurssi.
$valittukurssi</p>
Yes the above does display the parameter, because it is a client side WML var, but you cannot use this variable in the JSP code (that's why your SWL fails).
/'parameter read with JSP by generating WML with
JSP*/
out.println("<p>$valittukurssi</p>");Here's you're problem, the above line is EXACTLY the same as the one before it. When the container parses through this JSP code it translates the above line to:
<p>$valittukurssi</p> on the WML page and the CLIENT uses it's local variable to display it.
What you need and want is to have a variable that can be used in JSP code and output to your WML page. Here's how it's done:
out.println("<go href='#helpcard'>");
String some_name = "valittukurssi";
out.println("<setvar name='"+some_name+"'
value='$("+some_name+")'/>");
//note that you may have to escape the ( and ) with a \
//so we displayed the variable above into the WML page, now we can use it in the SQL query:
/* SQL query with JSP */
ResultSet uudettulokset =
uusilause.executeQuery("select * from kurssi where
lyhenne='"+some_name+"'");//the end of the command is: " ' " ) ;
Frank Krul
Got Node? -
How to compare result from sql query with data writen in html input tag?
how to compare result
from sql query with data
writen in html input tag?
I need to compare
user and password in html form
with all user and password in database
how to do this?
or put the resulr from sql query
in array
please help me?Hi dejani
first get the user name and password enter by the user
using
String sUsername=request.getParameter("name of the textfield");
String sPassword=request.getParameter("name of the textfield");
after executeQuery() statement
int exist=0;
while(rs.next())
String sUserId= rs.getString("username");
String sPass_wd= rs.getString("password");
if(sUserId.equals(sUsername) && sPass_wd.equals(sPassword))
exist=1;
if(exist==1)
out.println("user exist");
else
out.println("not exist"); -
I need your expert opinion on how to create a map with multiple conditions.
Hello.
I need your expert opinion on how to create a map with multiple conditions.
I have a procedure (which i cannot import or re-create in OWB due to the bug), so i am trying to create a map instead :-(
How can i create a cursors within the map?
My function creates table and cursor.
Then it will have to check for duplicates in the tables (the one created and another table) - the criteria for finding duplicates is a number of fields.I then need to place few different conditions (if some attributes are not available) and it has to load cursor based on this conditions. The next step is to fetch the data into the cursor based on what attributes are missing.
The next thing it will do is insert the data into table (if record doesn't exist), output the error in separate table is record is corrupted, or update the record with changed information.
In short i need to re-create match / merge but with conditions, iterations etc 'built into' it.
I can read up on available functions - it's just what would be the best options? and what would be the best approach to do so?
In my function i use %rowtype - but cannot use it in owb - so what would be the alternative? i don't really want to create a lot of variables and then have a nightmare of maintaing it. are there any tips regarding this?
having looked through Oracle dedupe - it's not really what i need because it is just DISTINCT.
I would appreciate any help / advise on this.
Thank you very muchthanks a lot for your reply - i will look into this option :-)
it is a bit more complicated now as i have to re-create the match / merge and then somehow 'tweak' it to achieve the result i need.
At the moment i am looking to breakdown the package into smaller chunks 'functions' and try creating the map that way.
Anyway, thank you very much for your suggestion. -
How could I replace hard coded value in my sql query with constant value?
Hi all,
Could anyone help me how to replace hardcoded value in my sql query with constant value that might be pre defined .
PROCEDURE class_by_day_get_bin_data
in_report_parameter_id IN NUMBER,
in_site_id IN NUMBER,
in_start_date_time IN TIMESTAMP,
in_end_date_time IN TIMESTAMP,
in_report_level_min IN NUMBER,
in_report_level_max IN NUMBER
IS
bin_period_length NUMBER(6,0);
BEGIN
SELECT MAX(period_length)
INTO bin_period_length
FROM bin_data
JOIN site_to_data_source_lane_v
ON bin_data.data_source_id = site_to_data_source_lane_v.data_source_id
JOIN bin_types
ON bin_types.bin_type = bin_data.bin_type
WHERE site_to_data_source_lane_v.site_id = in_site_id
AND bin_data.start_date_time >= in_start_date_time - numtodsinterval(1, 'DAY')
AND bin_data.start_date_time < in_end_date_time + numtodsinterval(1, 'DAY')
AND bin_data.bin_type = 2
AND bin_data.period_length <= 60;
--Clear the edr_class_by_day_bin_data temporary table and populate it with the data for the requested
--report.
DELETE FROM edr_class_by_day_bin_data;
SELECT site_to_data_source_lane_v.site_id,
site_to_data_source_lane_v.site_lane_id,
site_to_data_source_lane_v.site_direction_id,
site_to_data_source_lane_v.site_direction_name,
bin_data_set.start_date_time,
bin_data_set.end_date_time,
bin_data_value.bin_id,
bin_data_value.bin_value
FROM bin_data
JOIN bin_data_set
ON bin_data.bin_serial = bin_data_set.bin_serial
JOIN bin_data_value
ON bin_data_set.bin_data_set_serial = bin_data_value.bin_data_set_serial
JOIN site_to_data_source_lane_v
ON bin_data.data_source_id = site_to_data_source_lane_v.data_source_id
AND bin_data_set.lane = site_to_data_source_lane_v.data_source_lane_id
JOIN (
SELECT CAST(report_parameter_value AS NUMBER) lane_id
FROM report_parameters
WHERE report_parameters.report_parameter_id = in_report_parameter_id
AND report_parameters.report_parameter_group = 'LANE'
AND report_parameters.report_parameter_name = 'LANE'
) report_lanes
ON site_to_data_source_lane_v.site_lane_id = report_lanes.lane_id
JOIN (
SELECT CAST(report_parameter_value AS NUMBER) class_id
FROM report_parameters
WHERE report_parameters.report_parameter_id = in_report_parameter_id
AND report_parameters.report_parameter_group = 'CLASS'
AND report_parameters.report_parameter_name = 'CLASS'
) report_classes
ON bin_data_value.bin_id = report_classes.class_id
JOIN edr_rpt_tmp_inclusion_table
ON TRUNC(bin_data_set.start_date_time) = TRUNC(edr_rpt_tmp_inclusion_table.date_time)
WHERE site_to_data_source_lane_v.site_id = in_site_id
AND bin_data.start_date_time >= in_start_date_time - numtodsinterval(1, 'DAY')
AND bin_data.start_date_time < in_end_date_time + numtodsinterval(1, 'DAY')
AND bin_data_set.start_date_time >= in_start_date_time
AND bin_data_set.start_date_time < in_end_date_time
AND bin_data.bin_type = 2
AND bin_data.period_length = bin_period_length;
END class_by_day_get_bin_data;In the above code I'm using the hard coded value 2 for bin type
bin_data.bin_type = 2But I dont want any hard coded number or string in the query.
How could I replace it?
I defined conatant value like below inside my package body where the actual procedure comes.But I'm not sure whether I have to declare it inside package body or inside the procedure.
bin_type CONSTANT NUMBER := 2;But it does't look for this value. So I'm not able to get desired value for the report .
Thanks.
Edited by: user10641405 on May 29, 2009 1:38 PMDeclare the constant inside the procedure.
PROCEDURE class_by_day_get_bin_data(in_report_parameter_id IN NUMBER,
in_site_id IN NUMBER,
in_start_date_time IN TIMESTAMP,
in_end_date_time IN TIMESTAMP,
in_report_level_min IN NUMBER,
in_report_level_max IN NUMBER) IS
bin_period_length NUMBER(6, 0);
v_bin_type CONSTANT NUMBER := 2;
BEGIN
SELECT MAX(period_length)
INTO bin_period_length
FROM bin_data
JOIN site_to_data_source_lane_v ON bin_data.data_source_id =
site_to_data_source_lane_v.data_source_id
JOIN bin_types ON bin_types.bin_type = bin_data.bin_type
WHERE site_to_data_source_lane_v.site_id = in_site_id
AND bin_data.start_date_time >=
in_start_date_time - numtodsinterval(1, 'DAY')
AND bin_data.start_date_time <
in_end_date_time + numtodsinterval(1, 'DAY')
AND bin_data.bin_type = v_bin_type
AND bin_data.period_length <= 60;
--Clear the edr_class_by_day_bin_data temporary table and populate it with the data for the requested
--report.
DELETE FROM edr_class_by_day_bin_data;
INSERT INTO edr_class_by_day_bin_data
(site_id,
site_lane_id,
site_direction_id,
site_direction_name,
bin_start_date_time,
bin_end_date_time,
bin_id,
bin_value)
SELECT site_to_data_source_lane_v.site_id,
site_to_data_source_lane_v.site_lane_id,
site_to_data_source_lane_v.site_direction_id,
site_to_data_source_lane_v.site_direction_name,
bin_data_set.start_date_time,
bin_data_set.end_date_time,
bin_data_value.bin_id,
bin_data_value.bin_value
FROM bin_data
JOIN bin_data_set ON bin_data.bin_serial = bin_data_set.bin_serial
JOIN bin_data_value ON bin_data_set.bin_data_set_serial =
bin_data_value.bin_data_set_serial
JOIN site_to_data_source_lane_v ON bin_data.data_source_id =
site_to_data_source_lane_v.data_source_id
AND bin_data_set.lane =
site_to_data_source_lane_v.data_source_lane_id
JOIN (SELECT CAST(report_parameter_value AS NUMBER) lane_id
FROM report_parameters
WHERE report_parameters.report_parameter_id =
in_report_parameter_id
AND report_parameters.report_parameter_group = 'LANE'
AND report_parameters.report_parameter_name = 'LANE') report_lanes ON site_to_data_source_lane_v.site_lane_id =
report_lanes.lane_id
JOIN (SELECT CAST(report_parameter_value AS NUMBER) class_id
FROM report_parameters
WHERE report_parameters.report_parameter_id =
in_report_parameter_id
AND report_parameters.report_parameter_group = 'CLASS'
AND report_parameters.report_parameter_name = 'CLASS') report_classes ON bin_data_value.bin_id =
report_classes.class_id
JOIN edr_rpt_tmp_inclusion_table ON TRUNC(bin_data_set.start_date_time) =
TRUNC(edr_rpt_tmp_inclusion_table.date_time)
WHERE site_to_data_source_lane_v.site_id = in_site_id
AND bin_data.start_date_time >=
in_start_date_time - numtodsinterval(1, 'DAY')
AND bin_data.start_date_time <
in_end_date_time + numtodsinterval(1, 'DAY')
AND bin_data_set.start_date_time >= in_start_date_time
AND bin_data_set.start_date_time < in_end_date_time
AND bin_data.bin_type = v_bin_type
AND bin_data.period_length = bin_period_length;
END class_by_day_get_bin_data; -
Doubt in Firing Query with multiple opportunities UUID/IDs
HI Folks!
I might have simple doubt but please help me on this!
1. I have a custom BO with association to opportunities.
[DeploymentUnit(CustomerRelationshipManagement)] businessobject Sy_Trade {
[AlternativeKey] [Label("Trade Id")] element tradeid : BusinessTransactionDocumentID;
node RelatedOpportunities [0,n]{
element BusinessTransactionDocumentReference : BusinessTransactionDocumentReference;
element BusinessTransactionDocumentRelationshipRoleCode : BusinessTransactionDocumentRelationshipRoleCode;
association RelatedOpportunity[0,1] to Opportunity;
2. I have success fully used association and i am able to view create all the opportunities related to my custom Bo.
ISSUE : I want a facet where i just want DISPLAY the activities and sales document assigned in the RELATED OPPORTUNITIES ( N opportunities )
How do i query with Multiple opportunities ID and fetch the activities against it?
Btw I want to use query in UI Designer... I have created an advanced list pane and there i want the result list
I hope i am clear!
Thanks in adavance...
Regards
DhruvinHi Ludger,
I have successfully displayed Related Opportunities associated with trade.( i am able to create , delete also )
Issue : I am not able to "Display" ( i don't need to edit or create ) all the activities created against all the opportunities in a different tab.
I tried to approaches :
1: Query : Created a Query on Activity BO and tried to pass multiple related opportunities ( but seems not possible , please tell me any possibility to pass range of opportunity via transformation or anything? )
2 : binding : I have a Node Related Opportunity so just tried to bind it with BO model but problem is it is displaying all the activities of first opportunity of the list...
i think why because :
In Data model I have created a table bind with Related Opportunities...
now that node is 1 to N , association to opportunity 0 to 1 , hence i think it fetches only 1 opportunities activity
should i create like below ( Or is it possible)
Node Reltdoppts[0,1]
association [0,N] to opportunity BO ?
Although i strongly feel SAP should provied us two things :
1. We need to pass range of opportunities in a query.
2. We need to just write some absl code where i can fill the table and display it
and also is there any possibility to create a report or something to display activities as we just want to display the activities!
P.S : I have been getting a lot of bashing from client because some of the product restriction in cloud! i hope and wish SAP give developers free hand to develop right now its like our hands are tied to many things
Maybe you are looking for
-
Where is the Motion Interaction Panel?
It does not magically appear as suggested when I select a motion tween object or in the timeline. I would like to add some custom bounce easing. Seriously disappointed in Creative Cloud Flash.
-
Hi all! Searching with TREX return an error (found in TREXADMIN trace log): [4620] 2007-10-31 20:48:59.531 e TREXRfcDll rfddll.cpp(00867) : table size mismatch for SRET_INDEX_STORAGE_SEARCHING:DOCATTRTAB, rfc=29,exe=27 any suggestions
-
Problem to update my quicktime player
when I start the update process software arrives at a certain point that the computer looks for the file QuickTime.msi, but can not find it. I tried several times, including via download from Apple's Web site but the same thing happens. What can I do
-
Acs+wlc2106+ap+wet200-eap_tls
I have a problem with EAP-TLS in network consisting from ACS+WLC2106+AIR-LAP1242+WET200. Network is working - I mean APs are authenticated to WLC and there is a connectitivity if I try WPA preshared key. But with EAP-TLS ACS reports "EAP type not con
-
When I start up my Satellite Pro A60 I get to the Toshiba screen, then it goes to a blank screen and nothing else happens. I have tried removing the battery, disconnecting from the power outlet to no avail. I have powered up the laptop and pressed F1