SQL for Parnet child for range values
Gurus,
I need help to figure out a query which will result to get parent child relation for ranges of data
eg:
Name Low High
t1 10000 20000
t2 10000 20001
t3 11000 15000
t4 10500 19000
t5 11000 14500
Results
Name Parent Low High
T2 0 10000 20001
t1 t2 10000 20000
t3 t1 11000 15000
t4 t1 10500 19000
t5 t3 11000 15000
Child will have only one parent
please help
gbk
Well normally I would suggest using Start with/Connect by for a hierarchical query.
But you need to provide more accurate data. Somewhere in your table you must have a parent id.
So if you had that it would look something like:
select name, nvl(parent_name, 0) low, high
from table
start with parent_name is null
connect by name = prior parent_name
Similar Messages
-
Querying for first child node's value of a certain tag
Hi,
I am using the java parser 2 from Oracle. Given a XML document
containing the following
<course>
<Name>Calculus</Name>
<Dept>Math</Dept>
<Instructor>
<Name>Jim Green</Name>
</Instructor>
<Student>
<Name>Jack</Name>
<Name>Mary</Name>
<Name>Paul</Name>
</Student>
</course>
I want to efficiently obtain the value of first child node of
<course> whose tag is <Name>.
I could not find any mtd that can do that efficiently. The
nearest match is the mtd getElementsByTag("Name") which
traverses the entire tree under <course>.
Any help appreciated !
Thanks in advance
Mak
nullMak (guest) wrote:
: Hi,
: I am using the java parser 2 from Oracle. Given a XML document
: containing the following
: <course>
: <Name>Calculus</Name>
: <Dept>Math</Dept>
: <Instructor>
: <Name>Jim Green</Name>
: </Instructor>
: <Student>
: <Name>Jack</Name>
: <Name>Mary</Name>
: <Name>Paul</Name>
: </Student>
: </course>
: I want to efficiently obtain the value of first child node of
: <course> whose tag is <Name>.
: I could not find any mtd that can do that efficiently. The
: nearest match is the mtd getElementsByTag("Name") which
: traverses the entire tree under <course>.
: Any help appreciated !
: Thanks in advance
: Mak
Your best bet, if you do not need the entire tree, is to use the
SAX interface to return the desired data. Since it is event
driven it does not have to parser the while document.
Oracle XML Team
http://technet.oracle.com
Oracle Technology Network
null -
SQL Query to get Date Range Values
Hi,
The database is Oracle11i.
I am looking for a way to generate list of dates from a fixed date in the past (could be hardcoded) to current day (sysdate).
That is, if the fixed date is 19 June 2011 and assuming that today is 24 June 2011 the SQL should be able to generate the
following:-
19-June-2011
20-June-2011
21-June-2011
22-June-2011
23-June-2011
24-June-2011
And the constraint is that I can't make any change to the database in question. I can only fire an SQL query (SELECT). No
usage of time dimension kind of approach (time dimension is not available here) and no procedures, PL/SQL etc. Is there any way?
ThanksJaimeen Shah wrote:
Hi,
The database is Oracle11i.
I am looking for a way to generate list of dates from a fixed date in the past (could be hardcoded) to current day (sysdate).
That is, if the fixed date is 19 June 2011 and assuming that today is 24 June 2011 the SQL should be able to generate the
following:-
19-June-2011
20-June-2011
21-June-2011
22-June-2011
23-June-2011
24-June-2011
And the constraint is that I can't make any change to the database in question. I can only fire an SQL query (SELECT). No
usage of time dimension kind of approach (time dimension is not available here) and no procedures, PL/SQL etc. Is there any way?
Thanks
SQL> def date_start = '13/11/2010'
SQL> def date_end = '22/11/2010'
SQL> with
2 data as (
3 select to_date('&date_start', 'DD/MM/YYYY') date1,
4 to_date('&date_end', 'DD/MM/YYYY') date2
5 from dual
6 )
7 select to_char(date1+level-1, 'DD/MM/YYYY') the_date
8 from data
9 connect by level <= date2-date1+1
10 /
THE_DATE
13/11/2010
14/11/2010
15/11/2010
16/11/2010
17/11/2010
18/11/2010
19/11/2010
20/11/2010
21/11/2010
22/11/2010 -
Need PL/SQL Command for to check all rows value for child record and update
Hi All,
i want to update one field following by
one to many relationship for example
in child applet status field is value is "Closed" for all child record then parent value also should update to closed
Note: if one child record field status is "Open" don't do the update operationYou can do it in single UPDATE operation.
Here is sample & Result:
create table PA (id varchar2(3), name varchar2(12), STATUS varchar2(12));
insert into pa values('001','Cary','Open');
insert into pa values('002','TOM','Open');
create table boy (par_id varchar2(3), id varchar2(4), name varchar2(12), status varchar2(12));
insert into boy values('001','ABC1','Cary','Open');
insert into boy values('001','ABC2','Mac','Closed');
insert into boy values('001','ABC3','Ray','Closed');
insert into boy values('001','ABC4','NALLY','Open');
insert into boy values('002','ABC5','ME','Closed');
insert into boy values('002','ABC6','SHE','Closed');
UPDATE PA
SET STATUS='Closed'
WHERE NOT EXISTS
(SELECT 1
FROM BOY
WHERE BOY.PAR_ID=PA.id
GROUP BY BOY.PAR_ID,
BOY.STATUS
HAVING SUM(DECODE(BOY.STATUS,'Open',1,'Closed',0,0))>0
select * from pa;
001 Cary Open
002 TOM Closed -
Need to create a report to show values for a particular date range
I have to create a report, out of which I need two columns : << Customer Value Variance and Churn Score Variance >> to show values only for a custom date range, which will be entered via a dashboard prompt.
These generic date columns are not present and cannot be added. I have to make use of Pres variables
What I have currently done is:
1) Created a prompt with 2 different date columns and passing those values into variables vStartDate and vEndDate. (I don't actually need those 2 column which I have selelcted, but I have taken those so that I can prompt the values in calendar format and pass onto the variables)
2) Created report with necessary columns, with 2 extra columns (hidden) as vStart Date Column and vEnd Date Column which take the values from the presentation variables defined in the prompt. I have created these columns as then I can reference these in the two required columns if necessary.
I am already facing error in report after doing this and I am confused how to proceed. Any suggestions?
Thanks.Yes, but it only has one generic Date column, no start date and end date. I can't use that twice in the prompt. Although I can specify it to be 'between', but I'm not sure I can pass values to both variables like that.
Currently I have used Campaign Start Date and Campaign End Date to enter values in calender format to the variables. -
T-SQL and CLR types for return value do not match
Hi I am trying to create a CLR function to call a webservice, the CLR function return data type is double, whether I try
to create this as a table valued funcion or a scalar to return a distance travelled value I am receiving the error below. I've tried changing data types around in the CLR side and the SQL side but keep receiving the same error message, any help would be appreciated,
Thank you,
[Microsoft.SqlServer.Server.SqlFunction(Name = "DistanceCalc")]
public static Double DistanceCalc(Double SrcLat, Double SrcLong,
Double DestLat, Double DestLong)
MileageWS ws = new MileageWS();
ws.Url = "http://test.isp.ca/Distance.asmx";
int intUom = 0; // 0 = Mile, 1 = KM
RouteType RouteMethod = RouteType.Practical;
Requester RequestedFrom = Requester.LinkRoute;
Double distance;
distance = ws.GetDistanceInfoForLonLat(SrcLat, SrcLong, DestLat, DestLong, intUom, RouteMethod, RequestedFrom);
return distance;
CREATE FUNCTION DistanceCalc
@SrcLat as float, @SrcLong as float,
@DestLat as float, @DestLong as float
RETURNS TABLE (Distance float)
External NAME CLRfunctions.RIFunctions.DistanceCalc
GO
Error received when try to Create function ...
1, Level 16, State 2, Procedure pcMiler, Line 6
CREATE FUNCTION for "pcMiler" failed because T-SQL and CLR types for return value do not match.You defined at table-valued CLR function, but I think you meant to define a scalar CLR function. That might be the cause of the error.
RETURNS TABLE (Distance float)
should be
RETURNS (Distance float) -
Data truncation: Out of range value adjusted for column
I encountered the following error while working thru "Creating Your First LiveCyle ES Application" and have not been able to find a solution. Any assistance would be greatly appreciated.
javax.ejb.TransactionRolledbackLocalException: Data truncation: Out of range value adjusted for column 'loanamount' at row 1; CausedByException is:
Data truncation: Out of range value adjusted for column 'loanamount' at row 1
at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:247)
at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:335)
at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:166)
at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.java:153)
at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:192)
at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor. java:122)
at org.jboss.ejb.SessionContainer.internalInvoke(SessionContainer.java:624)
at org.jboss.ejb.Container.invoke(Container.java:873)
at org.jboss.ejb.plugins.local.BaseLocalProxyFactory.invoke(BaseLocalProxyFactory.java:415)
at org.jboss.ejb.plugins.local.StatelessSessionProxy.invoke(StatelessSessionProxy.java:88)
at $Proxy284.writeObject(Unknown Source)hmm, i have sloved the error already. I have make my longtitude double(40,20).
-
Defining Range values for a keyfigure
Hi Frnds,
I have a keyfigure which is populated at cube level for calculating total years of experience with routine.
In my query it is giving me perfect result. But I want to display the Years of experience between range values. i.e
For eg:
Range | Number of employees
<1 | 10
1-2 | 20
3-5 | 30
I have tried with conditions but it didnt work.
So how can I define ranges for a keyfiger?
Can any body pls give me solution for this.
Thanks,
SridharHi
You can get this by using restricted keyfigure.First you need to have a keyfigure for number of employees on which you can have restricted keyfigure restricting on years of experience.
Regards
Ravi -
PCC-F-02044, CMD-LINE: Illegal or out of range value for option
Good day,
I very new to Pro*C and its compiler, i was tasked to recompile a program from a previous developer and got stuck with the above mentioned problem.
The command i'm using to compile the program is: proc xxx.pc
This returns the illegal or out of range value error
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sqlda.h>
#include <sqlcpr.h>
#include <sqlca.h>
#include <stddef.h>
using namespace std;
char myfile[60];
char puk [][];
int last_col = 0;
int last_row = 0;
int line_nr = 0;
string line = "";
int main(int argc, char *argv[])
if (argc != 2)
return(1);
ifstream myfile;
myfile.open (argv[1],ios::in);
if (myfile.is_open())
while (! myfile.eof() )
//while(getline(myfile,line))
getline (myfile,line);
line_nr++; //counting number of lines
line = trim(line); //remove whitespaces
if (line == "\r" or line.length() == 0) {
continue; //ignore blank lines
if (line_nr == 1) {
last_col = 1;
last_row = 0;
puk [last_row][last_col] = line;
} else if (line_nr > 1 && line.substr(1,3) != 'OOF') {
last_col = last_col + 1;
puk [last_row][last_col] = line;
} else {
last_row = last_row + 1;
puk [last_row][1] = line;
myfile.close();
line_nr = 0;
return 0;
Any assistance will be appreciated.
Regards,My pcscfg.cfg file is set as follows:
sys_include=(/usr/include/c++/4.1.1/iostream,/usr/include/c++/4.1.1/backward/iostream.h,/usr/include/c++/4.1.1/fstream,/usr/include/c++/4.1.1/backward/fstrea
m.h,/usr/bin/strings,/usr/include/string.h,/usr/include/strings.h,/usr/include/stdio.h,/usr/lib/syslinux/com32/include/stdio.h,/oracle/client/9.2.0/precomp/p
ublic/sqlda.h,/oracle/client/9.2.0/precomp/public/sqlcpr.h,/oracle/client/9.2.0/precomp/public/sqlca.h,/usr/include/linux/stddef.h,/usr/lib/gcc/x86_64-redhat
-linux/4.1.1/include/stddef.h,/usr/lib/syslinux/com32/include/stddef.h,/usr/lib/syslinux/com32/include/bitsize/stddef.h,/usr/include,/usr/lib/gcc-lib/i386-re
dhat-linux/2.96/include,/oracle/app/oracle/client/precomp/public,/user/include/g++-3)
ltype=short -
How can I set range value in number in sql server
Hello,
I am using sql server 2012. I want to display range value in int column. Suppose I have a table which contains
columns called ID and dueDays. In dueDays there is data from 1 to 255 and slab range is
[7,15,30,60,150,250].
Now I want to display range as per duedays, suppose from 1 to 7 , it should display 7.
1-7 =
7
8-15 =
15
16-60 = 60
61-150 =150
151- 151-250 =250
>250 = >250
Here is code snippet for create table and insert record.
Create Table Tmp
ID int ,
DueDays int
GO
DECLARE @I INT = 1
WHILE @I <=255
BEGIN
INSERT INTO TMP VALUES (@I,@I)
SET @I=@I +1
END
Please also see attached image of required result.
Prem Shahhello Jingyan,
Thanks for reply but it doen't work in all case suppose range value is not exists in tmp then it is not working.
delete following record and check expected result is wrong .
delete from tmp where id in (3,7,15,30,60,150,250)
Prem Shah
Here is updated version:
Create Table Tmp ( ID int , DueDays int)
GO
DECLARE @I INT = 1
WHILE @I <=255
BEGIN
INSERT INTO TMP VALUES (@I,@I)
SET @I=@I +1
END
delete from tmp where id in (3,7,15,30,60,150,250)
--select * From Tmp
declare @range varchar(100)='3,7,15,30,60,150,250'
;with mySplit as (
SELECT distinct S.a.value('.', 'VARCHAR(100)') AS splitVal
FROM
(SELECT CAST (N'<H><r>' + REPLACE(@range, ',', '</r><r>')+ '</r></H>' AS XML) AS [vals] ) d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
,mycte as (
SELECT a.id, iSNULL(a.id,splitVal) id2, splitVal FROM tmp a
full outer JOIN mySplit as s ON Cast(splitVal as int)=a.DueDays)
--select * from mycte
Select id, ISNULL(rng ,255) rangeValues from mycte m
outer APPLY (SELECT TOP 1 splitVal FROM mycte
WHERE id2 >= m.id2 AND splitVal IS NOT NULL
ORDER BY id2 ) d( rng)
WHERE id is not null
Order by id
drop table tmp -
Order By Clause For Retrieving Child Elements
Hi All,
I got a toplink question regarding adding an order by clause for retrieving the child elements in a 1 to many mapping.
I have an Order with a collection of Order Events. ( one to many mapping). The OrderEvent model is the super class of all events and it is abstract. The mapping for the order event descriptors has a class hierarchy mapping which uses a table for its super class (i.e OrderEvent abstract class) and different tables for its sub class elements (e.g ShippingEvent, LifeCycleEvent etc which are concrete classes).
If I add an order by clause to order the event by a spuerClassProperty in the super class descriptor, it gets ignored and the ordering is done by the alphabetic order of the indicator field values.
I also noticed that if there is more than one sub class instance for a specific class indicator value, the ordering by is observed.
I got around it with a Comparator, but just want to know if it could be possible to achieve this with toplink.
Regards.Does the Order By appear on the SQL that get issued? TopLink only does ordering on the database, and not in memory. This means that subclass queries will be ordered per type, on not as one big list.
A Comparator is a good solution. -
How to find latest child for a given parent in same table?
More details:
Here I am giving an example -
Orig_ID Chg_to_ID
A B
B C
C D
D Null
From source I use to get Orig_ID values, using Orig_ID value have to find latest Child(Chg_to_ID) to that at any level.
Latest child identify by Null value in the column "Chg_to_ID".
If I get B --> need to replace B with D. I may get any value A or B or C or D -- but at an end I have to replace those values with 'D', since it is latest for any of those parents.
I tried to use "Connect By Prior", but it is tooo slow ofcourse query not returned after 10min also. Plz advise.First time every employee will be assingend an ID and may changed/merged to another ID basing on some other conditins. So, any time first assigned ID may changed to new ID and will be updated to another column "Chg_to_ID" as winner ID and at the same time one more records will be created with new ID as ID and Null in "Chg_to_ID".
In my first post, given an example, here pasting again:
Orig_ID Chg_to_ID
A-------------->B
B-------------->C
C-------------->D
D-------------->Null
In detail: One employee first assigned ID as "A" after wards changed to "B". At that time data would be like below
Orig_ID Chg_to_ID
A-------------->B
B-------------->Null
After that B change to C, now it looks like this:
Orig_ID Chg_to_ID
A-------------->B
B-------------->C
C-------------> Null
For each change one record will be inserted.
My requirement is -- Orig_ID may get A or B or C, but I need to replace those with "C", since it is latest child. For latest child "Chg_to_ID" is NULL.
Plz let me know for any clarifications. -
How to get the weekends days for a specific date range
I want to select list of only weekend dates from a given date range. Is it possible in SQL?
For example if the range is '08/01/2011' and '08/30/2011'
I want a list
08/06/2011
08/07/2011
08/13/2011
08/14/2011
08/20/2011
08/21/2011
08/27/2011
08/28/2011Thank You, Naveen email:[email protected]First and easy to do is having a Calendar table, which over there you can have those information.
http://arbibaghdanian.blogspot.com/2011/05/calendar-table.html
Declare @beginDate Date, @EndDate Date
Select @beginDate = '08/01/2011', @EndDate = '08/31/2011'
Declare @Calendar Table
(CalendarDate Date Primary key, IsWeekend Bit, YearNo SmallInt, QuarterNo TinyInt, MonthNo TinyInt, DayOfYearNo SmallInt, DayNo TinyInt, WeekNo TinyInt, WeekDayNo TinyInt)
While @beginDate <= @endDate
Begin
Insert Into @Calendar
Select
@beginDate As CalendarDate
,(Case When DATEPART(Weekday, @beginDate) In (7, 1) Then 1 Else 0 End) As IsWeekend
,DATEPART(Year, @beginDate) As YearNo
,DATEPART(QUARTER, @beginDate) As QuarterNo
,DATEPART(MONTH, @beginDate) As MonthNo
,DATEPART(DayOfYear, @beginDate) As DayOfYearNo
,DATEPART(Day, @beginDate) As DayNo
,DATEPART(Week, @beginDate) As WeekNo
,DATEPART(WEEKDAY, @beginDate) As WeekDayNo
Set @beginDate = DateAdd(Day, 1, @beginDate)
End
Select * From @Calendar Where IsWeekend = 1
Best Wishes, Arbi --- MCC 2011; Please vote if you find this posting was helpful or Mark it as answered. -
Can we implement the custom sql query in CR for joining the two tables
Hi All,
Is there anyway to implement the custom sql query in CR for joining the two tables?
My requirement here is I need to write sql logics for joining the two tables...
Thanks,
GanaIn the Database Expert, expand the Create New Connection folder and browse the subfolders to locate your data source.
Log on to your data source if necessary.
Under your data source, double-click the Add Command node.
In the Add Command to Report dialog box, enter an appropriate query/command for the data source you have opened.
For example:
SELECT
Customer.`Customer ID`,
Customer.`Customer Name`,
Customer.`Last Year's Sales`,
Customer.`Region`,
Customer.`Country`,
Orders.`Order Amount`,
Orders.`Customer ID`,
Orders.`Order Date`
FROM
Customer Customer INNER JOIN Orders Orders ON
Customer.`Customer ID` = Orders.`Customer ID`
WHERE
(Customer.`Country` = 'USA' OR
Customer.`Country` = 'Canada') AND
Customer.`Last Year's Sales` < 10000.
ORDER BY
Customer.`Country` ASC,
Customer.`Region` ASC
Note: The use of double or single quotes (and other SQL syntax) is determined by the database driver used by your report. You must, however, manually add the quotes and other elements of the syntax as you create the command.
Optionally, you can create a parameter for your command by clicking Create and entering information in the Command Parameter dialog box.
For more information about creating parameters, see To create a parameter for a command object.
Click OK.
You are returned to the Report Designer. In the Field Explorer, under Database Fields, a Command table appears listing the database fields you specified.
Note:
To construct the virtual table from your Command, the command must be executed once. If the command has parameters, you will be prompted to enter values for each one.
By default, your command is called Command. You can change its alias by selecting it and pressing F2. -
Script for master child relation
we need script for maste child relation
if i insert or delete or update in master table it should reflect in child table after running procedure (not trigger).
fetch the value from master table and insert into child table using cursor.
for ex:
if i insert value in master table tab1 with column name emp_id, it should reflect other child table with the same column name emp_id.
insertions should only be done in master table. not in child table..
notes:it should be in cursorhallo
This is our procedure.the procedure works fine for loop 3 with cursor c3.
The other cursor 1 and cursor 2 are not working fine. they are fetching duplicate values(ex:D10,D10........).
In this procedure we are fetching values from 3 tables and putting values in a single table.
please find the solution the code is given below.
code
create or replace procedure employee_insert
is
cursor c1 is
select * from department where
not exists (select null from employee where employee.department_id=department.department_id);
p1 department%rowtype;
cursor c2 is
select * from jobs where
not exists (select null from employee where employee.job_id=jobs.job_id or employee.job_title=jobs.job_title);
p2 jobs%rowtype;
cursor c3 is
select * from project where
not exists (select null from employee where employee.proj_id=project.proj_id or employee.proj_name=project.proj_name);
p3 project%rowtype;
begin
for p1 in c1
loop
for p2 in c2
loop
for p3 in c3
loop
insert into employee (EMPLOYEE_ID,EMPLOYEE_NAME,
department_id,department_name,
DATE_OF_BIRTH,job_id,job_title,
HIRE_DATE,
SALARY,proj_id,proj_name,
PHONE_NUMBER,
ADDRESS,EMAIL) values('E'||employee_id_seq.nextval,
dbms_random.string('A', 8),
p1.department_id,
p1.department_name,
TO_DATE(TRUNC(DBMS_RANDOM.VALUE(2452641,2452641+364)),'J'),p2.job_id,p2.job_title,
TO_DATE(TRUNC(DBMS_RANDOM.VALUE(2452641,2452641+364)),'J'),
Round(DBMS_Random.value(10,50)),
p3.proj_id,p3.proj_name,
'98'||'42'||Round(DBMS_Random.value(1000,5000)),
dbms_random.string('A', 20),
dbms_random.string('A', 8));
end loop;
end loop;
end loop;
Exception
When others then
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
End;
execute employee_insert;
/
Maybe you are looking for
-
Firefox 32 hangs on "Save Image" dialogue box Windows 8.1..Tried everything
I clean installed windows 8.1.. then installed all latest drivers for my devices... installed latest Firefox.. Then i needed some images ..so opened Google image search and searched images..opened one image in a New Tab.. clicked "View Image" and tri
-
3.6.25 was just installed today. When I opened up my Comcast email account (webmail) in Firefox, every email had a check mark in front of it. When I open the account in IE8 there are no check marks. And I don't seem to be able to sign out when in Fir
-
How to send only email from workflow
Hi Guys, I want to send an email from a workflow without sending a notification ... how do i do it ? Thanks In advance Tom.
-
My question is what if I have troubleshooted with holding the sleep/awake button and power and it's not changing to any other screen what should I do? It doesn't even show the battery strength wheither its completely dead or charging at all.
-
Selection tool turns into pencil on MacBook Air
I'm using illustrator cc on a MacBook air. When I try to use the selection tool, It turns into a pencil and becomes useless.