Query help with Model clause
Hi Gurus,
Can someone please help me out.
I've a below tables.
1) tbl_link --> this table contains information at profile level
2) tbl_summary --> this table contains summary at parent profile level derived from tbl_link table
One parent profile contains multiple child profiles and each child profile links to a code (which is B, W, G or P) and the code is linked to a category (i.e. ONL and OFL). In this case code B is linked to category 'ONL' and codes W,G,P linked to OFL category.
ONL category needs 100 points. If it don't have enough points then i need to borrow from OFL category which i'm doing and populating into tbl_summary table at parent profile level.
Now i need to insert data into tbl_link table at profile level with howmany points used, expired based on tbl_summary table. Rule is at the end of month if we add points for each profile in tbl_link table it should come as 0.
with
tbl_SUMMARY as
select 1 as ppid,'ONL' as catgcode, 53 as earned_points,47 BORROWED_POINTS,100 CERT_POINTS,0 DISCARD_POINTS,100 used from dual
union
select 1 as ppid,'OFL' as catgcode, 223 as earned_points,0 BORROWED_POINTS,176 CERT_POINTS,76 DISCARD_POINTS,100 used from dual
union
select 2 as ppid,'ONL' as catgcode, 39 as earned_points,61 BORROWED_POINTS,100 CERT_POINTS,0 DISCARD_POINTS,100 used from dual
union
select 2 as ppid,'OFL' as catgcode, 90 as earned_points,0 BORROWED_POINTS,29 CERT_POINTS,29 DISCARD_POINTS,100 used from dual
union
select 3 as ppid,'ONL' as catgcode, 109 as earned_points,0 BORROWED_POINTS,109 CERT_POINTS,9 DISCARD_POINTS,100 used from dual
union
select 3 as ppid,'OFL' as catgcode, 223 as earned_points,0 BORROWED_POINTS,223 CERT_POINTS,23 DISCARD_POINTS,200 used from dual
union
select 4 as ppid,'ONL' as catgcode, 109 as earned_points,0 BORROWED_POINTS,109 CERT_POINTS,9 DISCARD_POINTS,100 used from dual
union
select 4 as ppid,'OFL' as catgcode, 169 as earned_points,0 BORROWED_POINTS,169 CERT_POINTS,69 DISCARD_POINTS,100 used from dual
tbl_link as
select 1 as ppid,1 as pid, 'B' as code,'ONL' as catgcode, 53 as earned_points from dual
union
select 1 as ppid,12 as pid, 'W' as code,'OFL' as catgcode, 26 as earned_points from dual
union
select 1 as ppid,13 as pid, 'G' as code,'OFL' as catgcode, 87 as earned_points from dual
union
select 1 as ppid,14 as pid, 'P' as code,'OFL' as catgcode, 110 as earned_points from dual
union
select 2 as ppid,2 as pid, 'B' as code,'ONL' as catgcode, 39 as earned_points from dual
union
select 2 as ppid,22 as pid, 'W' ,'OFL' as catgcode, 30 as earned_points from dual
union
select 2 as ppid,23 as pid, 'G' ,'OFL' as catgcode, 29 as earned_points from dual
union
select 2 as ppid,24 as pid, 'P' ,'OFL' as catgcode, 31 as earned_points from dual
union
select 3 as ppid,3 as pid, 'B' as code,'ONL' as tier_catgcode, 109 as earned_points from dual
union
select 3 as ppid,32 as pid, 'W' ,'OFL' , 26 as earned_points from dual
union
select 3 as ppid,33 as pid, 'G' ,'OFL', 87 as earned_points from dual
union
select 3 as ppid,34 as pid, 'P' ,'OFL' , 110 as earned_points from dual
union
select 4 as ppid,4 as pid, 'B' as code,'ONL' as catgcode, 109 as earned_points from dual
union
select 4 as ppid,42 as pid, 'W' as code,'OFL' , 26 as earned_points from dual
union
select 4 as ppid,43 as pid, 'G' as code,'OFL' , 87 as earned_points from dual
union
select 4 as ppid,44 as pid, 'P' as code,'OFL' , 56 as earned_points from dual
final (PARENT_PROFILE_ID,PROFILE_ID,catgcode,EARNED_POINTS,BORROWED_POINTS,CERT_POINTS,DISCARD_POINTS,USED)
as (
select A.PPID PARENT_PROFILE_ID,B.PID PROFILE_ID,A.catgcode,B.EARNED_POINTS,BORROWED_POINTS,CERT_POINTS,DISCARD_POINTS,USED
from tbl_SUMMARY a,tbl_link b where a.ppid=b.ppid AND A.catgcode=B.catgcode
ORDER BY PROFILE_ID
select * from final order by 1;
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED
1 1 ONL 53 47 100 0 100
1 14 OFL 110 0 176 76 100
1 13 OFL 87 0 176 76 100
1 12 OFL 26 0 176 76 100
2 2 ONL 39 61 100 0 100
2 24 OFL 31 0 29 29 100
2 23 OFL 29 0 29 29 100
2 22 OFL 30 0 29 29 100
3 32 OFL 26 0 223 23 200
3 33 OFL 87 0 223 23 200
3 34 OFL 110 0 223 23 200
3 3 ONL 109 0 109 9 100
4 42 OFL 26 0 169 69 100
4 43 OFL 87 0 169 69 100
4 44 OFL 56 0 169 69 100
4 4 ONL 109 0 109 9 100
Need Output as below :
For parent profile 1, whatever i mentioned above is not correct. Borrowed 47 points from OFL to ONL to make ONL and also from OFL category has 176 points remaining after lending to ONL and using only 100 points, remaining 76 points are discarded. Need to deduct these 76 points also from child profiles. Output will be as below.
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED BURN_PTS EXPIRE_PTS
1 1 ONL 53 47 100 0 100 -53 0
1 12 OFL 26 0 176 76 100 -26 0
1 13 OFL 87 0 176 76 100 -74 -13
1 14 OFL 110 0 176 76 100 -47 -63
For parent profile id 2 --> ONL category has 39 points, so borrowed 61 points from OFL category to make ONL points 100.
Now need to populate tbl_link table at child profile level (i.e. child profiles 22,23,24).
Borrowed 61 points from OFL and need to deduct this points from the profile which has highest earned points, in this case deduct from profile 24 which has 31 points, from profile 22 which has 30 points. Need output like below
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED BURN_PTS EXPIRE_PTS
2 2 ONL 39 61 100 0 100 -39 0
2 22 OFL 30 0 29 29 100 -30 0
2 23 OFL 29 0 29 29 100 0 -29
2 24 OFL 31 0 29 29 100 -31 0
For parent profile id 3 --> ONL category has 109 points, so no need to borrow points from OFL category
Now need to populate tbl_link table at child profile level (i.e. child profiles 32,33,34).
in this case ONL has 100 points, so move the remaining 9 points will be expired. OFL category has 223 points total. need only 200 points (i.e. mutiple of 100) for our process, 23 points will be expired and has to deduct from the profile which has highest earned points, in this case from profile 34. Output :
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED BURN_PTS EXPIRE_PTS
3 3 ONL 109 0 109 9 100 -100 -9
3 32 OFL 26 0 223 23 200 -26 0
3 33 OFL 87 0 223 23 200 -87 0
3 34 OFL 110 0 223 23 200 -87 -23
For parent profile id 4 --> ONL category has 109 points, so no need to borrow points from OFL category
Now need to populate tbl_link table at child profile level (i.e. child profiles 42,43,44).
in this case ONL has 100 points, so move the remaining 9 points will be expired. OFL category has 169 points total. need only 100 points (i.e. mutiple of 100) for our process, 69 points will be expired and has to deduct from the profile which has highest earned points, in this case from profile 43. Output :
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED BURN_PTS EXPIRE_PTS
4 4 ONL 109 0 109 9 100 100 9
4 42 OFL 26 0 169 69 100 -26 0
4 43 OFL 87 0 169 69 100 -18 -69
4 44 OFL 56 0 169 69 100 -56 0
Can someone help with the query. I googled about looping in sql and came to know that Oracle has a feature MODEL to loop in SQL, but i don't have idea on using MODEL clause.
Appreciate your help!
Thanks
Sri
Hi Gurus,
Can someone please help me out.
I've a below tables.
1) tbl_link --> this table contains information at profile level
2) tbl_summary --> this table contains summary at parent profile level derived from tbl_link table
One parent profile contains multiple child profiles and each child profile links to a code (which is B, W, G or P) and the code is linked to a category (i.e. ONL and OFL). In this case code B is linked to category 'ONL' and codes W,G,P linked to OFL category.
ONL category needs 100 points. If it don't have enough points then i need to borrow from OFL category which i'm doing and populating into tbl_summary table at parent profile level.
Now i need to insert data into tbl_link table at profile level with howmany points used, expired based on tbl_summary table. Rule is at the end of month if we add points for each profile in tbl_link table it should come as 0.
with
tbl_SUMMARY as
select 1 as ppid,'ONL' as catgcode, 53 as earned_points,47 BORROWED_POINTS,100 CERT_POINTS,0 DISCARD_POINTS,100 used from dual
union
select 1 as ppid,'OFL' as catgcode, 223 as earned_points,0 BORROWED_POINTS,176 CERT_POINTS,76 DISCARD_POINTS,100 used from dual
union
select 2 as ppid,'ONL' as catgcode, 39 as earned_points,61 BORROWED_POINTS,100 CERT_POINTS,0 DISCARD_POINTS,100 used from dual
union
select 2 as ppid,'OFL' as catgcode, 90 as earned_points,0 BORROWED_POINTS,29 CERT_POINTS,29 DISCARD_POINTS,100 used from dual
union
select 3 as ppid,'ONL' as catgcode, 109 as earned_points,0 BORROWED_POINTS,109 CERT_POINTS,9 DISCARD_POINTS,100 used from dual
union
select 3 as ppid,'OFL' as catgcode, 223 as earned_points,0 BORROWED_POINTS,223 CERT_POINTS,23 DISCARD_POINTS,200 used from dual
union
select 4 as ppid,'ONL' as catgcode, 109 as earned_points,0 BORROWED_POINTS,109 CERT_POINTS,9 DISCARD_POINTS,100 used from dual
union
select 4 as ppid,'OFL' as catgcode, 169 as earned_points,0 BORROWED_POINTS,169 CERT_POINTS,69 DISCARD_POINTS,100 used from dual
tbl_link as
select 1 as ppid,1 as pid, 'B' as code,'ONL' as catgcode, 53 as earned_points from dual
union
select 1 as ppid,12 as pid, 'W' as code,'OFL' as catgcode, 26 as earned_points from dual
union
select 1 as ppid,13 as pid, 'G' as code,'OFL' as catgcode, 87 as earned_points from dual
union
select 1 as ppid,14 as pid, 'P' as code,'OFL' as catgcode, 110 as earned_points from dual
union
select 2 as ppid,2 as pid, 'B' as code,'ONL' as catgcode, 39 as earned_points from dual
union
select 2 as ppid,22 as pid, 'W' ,'OFL' as catgcode, 30 as earned_points from dual
union
select 2 as ppid,23 as pid, 'G' ,'OFL' as catgcode, 29 as earned_points from dual
union
select 2 as ppid,24 as pid, 'P' ,'OFL' as catgcode, 31 as earned_points from dual
union
select 3 as ppid,3 as pid, 'B' as code,'ONL' as tier_catgcode, 109 as earned_points from dual
union
select 3 as ppid,32 as pid, 'W' ,'OFL' , 26 as earned_points from dual
union
select 3 as ppid,33 as pid, 'G' ,'OFL', 87 as earned_points from dual
union
select 3 as ppid,34 as pid, 'P' ,'OFL' , 110 as earned_points from dual
union
select 4 as ppid,4 as pid, 'B' as code,'ONL' as catgcode, 109 as earned_points from dual
union
select 4 as ppid,42 as pid, 'W' as code,'OFL' , 26 as earned_points from dual
union
select 4 as ppid,43 as pid, 'G' as code,'OFL' , 87 as earned_points from dual
union
select 4 as ppid,44 as pid, 'P' as code,'OFL' , 56 as earned_points from dual
final (PARENT_PROFILE_ID,PROFILE_ID,catgcode,EARNED_POINTS,BORROWED_POINTS,CERT_POINTS,DISCARD_POINTS,USED)
as (
select A.PPID PARENT_PROFILE_ID,B.PID PROFILE_ID,A.catgcode,B.EARNED_POINTS,BORROWED_POINTS,CERT_POINTS,DISCARD_POINTS,USED
from tbl_SUMMARY a,tbl_link b where a.ppid=b.ppid AND A.catgcode=B.catgcode
ORDER BY PROFILE_ID
select * from final order by 1;
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED
1 1 ONL 53 47 100 0 100
1 14 OFL 110 0 176 76 100
1 13 OFL 87 0 176 76 100
1 12 OFL 26 0 176 76 100
2 2 ONL 39 61 100 0 100
2 24 OFL 31 0 29 29 100
2 23 OFL 29 0 29 29 100
2 22 OFL 30 0 29 29 100
3 32 OFL 26 0 223 23 200
3 33 OFL 87 0 223 23 200
3 34 OFL 110 0 223 23 200
3 3 ONL 109 0 109 9 100
4 42 OFL 26 0 169 69 100
4 43 OFL 87 0 169 69 100
4 44 OFL 56 0 169 69 100
4 4 ONL 109 0 109 9 100
Need Output as below :
For parent profile 1, whatever i mentioned above is not correct. Borrowed 47 points from OFL to ONL to make ONL and also from OFL category has 176 points remaining after lending to ONL and using only 100 points, remaining 76 points are discarded. Need to deduct these 76 points also from child profiles. Output will be as below.
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED BURN_PTS EXPIRE_PTS
1 1 ONL 53 47 100 0 100 -53 0
1 12 OFL 26 0 176 76 100 -26 0
1 13 OFL 87 0 176 76 100 -74 -13
1 14 OFL 110 0 176 76 100 -47 -63
For parent profile id 2 --> ONL category has 39 points, so borrowed 61 points from OFL category to make ONL points 100.
Now need to populate tbl_link table at child profile level (i.e. child profiles 22,23,24).
Borrowed 61 points from OFL and need to deduct this points from the profile which has highest earned points, in this case deduct from profile 24 which has 31 points, from profile 22 which has 30 points. Need output like below
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED BURN_PTS EXPIRE_PTS
2 2 ONL 39 61 100 0 100 -39 0
2 22 OFL 30 0 29 29 100 -30 0
2 23 OFL 29 0 29 29 100 0 -29
2 24 OFL 31 0 29 29 100 -31 0
For parent profile id 3 --> ONL category has 109 points, so no need to borrow points from OFL category
Now need to populate tbl_link table at child profile level (i.e. child profiles 32,33,34).
in this case ONL has 100 points, so move the remaining 9 points will be expired. OFL category has 223 points total. need only 200 points (i.e. mutiple of 100) for our process, 23 points will be expired and has to deduct from the profile which has highest earned points, in this case from profile 34. Output :
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED BURN_PTS EXPIRE_PTS
3 3 ONL 109 0 109 9 100 -100 -9
3 32 OFL 26 0 223 23 200 -26 0
3 33 OFL 87 0 223 23 200 -87 0
3 34 OFL 110 0 223 23 200 -87 -23
For parent profile id 4 --> ONL category has 109 points, so no need to borrow points from OFL category
Now need to populate tbl_link table at child profile level (i.e. child profiles 42,43,44).
in this case ONL has 100 points, so move the remaining 9 points will be expired. OFL category has 169 points total. need only 100 points (i.e. mutiple of 100) for our process, 69 points will be expired and has to deduct from the profile which has highest earned points, in this case from profile 43. Output :
PARENT_PROFILE_ID PROFILE_ID CATGCODE EARNED_POINTS BORROWED_POINTS CERT_POINTS DISCARD_POINTS USED BURN_PTS EXPIRE_PTS
4 4 ONL 109 0 109 9 100 100 9
4 42 OFL 26 0 169 69 100 -26 0
4 43 OFL 87 0 169 69 100 -18 -69
4 44 OFL 56 0 169 69 100 -56 0
Can someone help with the query. I googled about looping in sql and came to know that Oracle has a feature MODEL to loop in SQL, but i don't have idea on using MODEL clause.
Appreciate your help!
Thanks
Sri
Similar Messages
-
Using the Case clause with Model clause
Hello PL SQL gurus
I've used some scripts I've found on these forums to create a mortgage amortization statement. What I am trying to accomplish is getting the script to run a calculation or use a value within a table based upon the value in that table.
Here are the two tables:
CREATE TABLE mortgage_facts (customer VARCHAR2(20), fact VARCHAR2(20),
amount NUMBER(10,3));
INSERT INTO mortgage_facts VALUES ('Smith', 'Loan', 131828.81);
INSERT INTO mortgage_facts VALUES ('Smith', 'Annual_Interest', 3.348);
INSERT INTO mortgage_facts VALUES ('Smith', 'Payments', 72);
INSERT INTO mortgage_facts VALUES ('Smith', 'PaymentAmt', 0);
CREATE TABLE mortgage (customer VARCHAR2(20), pmt_num NUMBER(4), principalp NUMBER(10,3), interestp NUMBER(10,3), mort_balance NUMBER(10,3));
INSERT INTO mortgage VALUES ('Smith',0, 0, 0, 131828.81);
If the value within the table mortgage_facts is zero, I want the script to run a calculation to be used in a MODEL clause. If it is not zero, I would like to use that value instead of the calculation. Below is the script that I am getting an error on (I have bolded the portion in question):
SELECT c, p, to_char(round(m,2),'fm$9999999.00') principal_balance,
to_char(round(pp,2),'fm$9999999.00') towards_principal,
to_char(round(ip,2),'fm$9999999.00') towards_interest,
to_char(round(mp,2),'fm$9999999.00') monthly_payment
FROM MORTGAGE
MODEL --See 1
IGNORE NAV
REFERENCE R ON
*(SELECT customer, fact, amt --See 2*
FROM mortgage_facts
*MODEL DIMENSION BY (customer, fact) MEASURES (amount amt) --See 3*
RULES SEQUENTIAL ORDER
CASE WHEN mortgage_facts.fact = 'PaymentAmt' AND mortage_facts.amt = 0 THEN
*amt[ANY, 'PaymentAmt'] = mortgage_facts.amt*
ELSE
*amt[any, 'PaymentAmt']= (amt[CV(),'Loan']**
*Power(1+ (amt[CV(),'Annual_Interest']/100/12),*
*amt[CV(),'Payments']) **
*(amt[CV(),'Annual_Interest']/100/12)) /*
*(Power(1+(amt[CV(),'Annual_Interest']/100/12),*
*amt[CV(),'Payments']) - 1)*
END
DIMENSION BY (customer cust, fact) measures (amt)
MAIN amortization
PARTITION BY (customer c)
DIMENSION BY (0 p)
MEASURES (principalp pp, interestp ip, mort_balance m, customer mc, 0 mp )
RULES SEQUENTIAL ORDER
ITERATE(1000) UNTIL (ITERATION_NUMBER+1 =
r.amt[mc[0],'Payments'])
(ip[ITERATION_NUMBER+1] = m[CV()-1] *
r.amt[mc[0], 'Annual_Interest']/1200,
mp[ITERATION_NUMBER+1] = r.amt[mc[0], 'PaymentAmt'],
pp[ITERATION_NUMBER+1] = r.amt[mc[0], 'PaymentAmt'] - ip[CV()],
m[ITERATION_NUMBER+1] = m[CV()-1] - pp[CV()]
ORDER BY c, p
Any help is much appreciated. Thank you!!Ok, here we go, one way with iterative model:
select *
from mortgage_facts
model
partition by (Customer)
dimension by (1 p)
measures(loan, payments, INTEREST, PAYMENTAMT, INTERESTPMT, PRINCIPALPMT, balance)
rules iterate(1e9) until (iteration_number+2 >= payments[1])
(loan[iteration_number+2]=loan[1]
,payments[iteration_number+2]=cv(p)-1
,interest[iteration_number+2]=interest[1]
,paymentamt[iteration_number+2]=ROUND(
(LOAN[1] * (INTEREST[1]/12/100)*Power((1+INTEREST[1]/12/100), PAYMENTS[1])/(Power((1+INTEREST[1]/12/100),PAYMENTS[1])-1)), 2)
,INTERESTPMT[iteration_number+2]=round(balance[cv(p)-1]*interest[1]/1200, 2)
,PRINCIPALPMT[iteration_number+2]=paymentamt[cv()]-INTERESTPMT[cv()]
,balance[iteration_number+2]=balance[cv()-1]-PRINCIPALPMT[cv()]
CUSTOMER P LOAN PAYMENTS INTEREST PAYMENTAMT INTERESTPMT PRINCIPALPMT BALANCE
Smith 1 131828.81 72 3.348 0 0 0 131828.81
Smith 2 131828.81 1 3.348 2023.55 367.8 1655.75 130173.06
Smith 3 131828.81 2 3.348 2023.55 363.18 1660.37 128512.69
Smith 4 131828.81 3 3.348 2023.55 358.55 1665 126847.69
Smith 5 131828.81 4 3.348 2023.55 353.91 1669.64 125178.05
Smith 6 131828.81 5 3.348 2023.55 349.25 1674.3 123503.75
Smith 7 131828.81 6 3.348 2023.55 344.58 1678.97 121824.78
Smith 8 131828.81 7 3.348 2023.55 339.89 1683.66 120141.12
Smith 9 131828.81 8 3.348 2023.55 335.19 1688.36 118452.76
Smith 10 131828.81 9 3.348 2023.55 330.48 1693.07 116759.69
Smith 11 131828.81 10 3.348 2023.55 325.76 1697.79 115061.9
Smith 12 131828.81 11 3.348 2023.55 321.02 1702.53 113359.37
Smith 13 131828.81 12 3.348 2023.55 316.27 1707.28 111652.09
Smith 14 131828.81 13 3.348 2023.55 311.51 1712.04 109940.05
.... -
Query Help with Parent, Child, Child's Child
Hi all,
Need some help with a query. I'm trying to create a stored procedure that is sort of like a Customer, Order, Order, Details. In my situation the tables are different but nevertheless, I want to grab all the fields from the Parent, Child,
and Childs' Child, where the Parent.ParentID = @Parameter. I tried this:
CREATE PROCEDURE [dbo].[spGetCompleteProjectXML]
@ProjectID int = 0
AS
SELECT *,
(SELECT *,
(SELECT *
FROM PageControls
WHERE (PageControls.ProjectPageID = ProjectPages.ProjectPageID))
FROM ProjectPages
WHERE (ProjectPages.ProjectID = @ProjectID))
FROM Projects
WHERE (ProjectID = @ProjectID)
FOR XML AUTO, ELEMENTS
RETURN 0
I think I'm close, but it was my best effort. Could someone help?
thanks in advanceHi TPolo,
Regarding your description, are you looking for a sample like below?
CREATE TABLE customer(customerID INT, name VARCHAR(99))
INSERT INTO customer VALUES(1,'Eric')
INSERT INTO customer VALUES(2,'Nelson')
CREATE TABLE orders(orderID INT,customerID INT)
INSERT INTO orders VALUES(1,1);
INSERT INTO orders VALUES(2,1)
INSERT INTO orders VALUES(3,2)
INSERT INTO orders VALUES(4,2)
CREATE TABLE orderDetails(orderID INT,item VARCHAR(99))
INSERT INTO orderDetails VALUES(1,'APPLE1')
INSERT INTO orderDetails VALUES(1,'BANANA1')
INSERT INTO orderDetails VALUES(2,'APPLE2')
INSERT INTO orderDetails VALUES(2,'BANANA2')
INSERT INTO orderDetails VALUES(3,'APPLE3')
INSERT INTO orderDetails VALUES(3,'BANANA3')
INSERT INTO orderDetails VALUES(4,'APPLE4')
INSERT INTO orderDetails VALUES(4,'BANANA5')
SELECT customer.customerID,customer.name,
(SELECT orderId,
SELECT item FROM orderDetails WHERE orderID=orders.orderID FOR XML AUTO,TYPE,ELEMENTS
FROM orders Where customerID=customer.customerID FOR XML AUTO,TYPE,ELEMENTS)
FROM customer WHERE customerID=1
FOR XML AUTO,ELEMENTS
DROP TABLE customer,orderDetails,orders
If you have any feedback on our support, please click
here.
Eric Zhang
TechNet Community Support -
Query Help with Item Master & Warehouse Code
Forum,
I would like help with a query to identify any items within a database where a particular warehouse code does NOT exist against it. At present I have the following:
select T0.ItemCode, T1.WhsCode from OITM T0
INNER JOIN OITW T1 on T0.ItemCode = T1.ItemCode
where T0.ItemCode NOT IN ('WHS1')
This is returning all other instance and not just a list of item codes where 'WHS1' is missing from within the 'Stock Data' tab.
Thanks,
SarahHi Sarah...
Try This
SELECT T0.ItemCode, T0.ItemName, T1.WhsCode
FROM OITM T0 INNER JOIN OITW T1 ON T0.ItemCode = T1.ItemCode
WHERE T1.WhsCode not in ( 'WHS1')
Regards
Kennedy -
Compute totals and subtotals with model clause
Please help,
I am using the model clause for the first time and need something like this, but no rule definition for every deptno:
SQL> select deptno, empno, ename, sal
2 from emp
3 model
4 dimension by (deptno, empno, ename)
5 measures(sal)
6 rules (
7 sal[10, null, 'ZZ-Sum'] = sum(sal)[10, any, any]
8 ,sal[20, null, 'ZZ-Sum'] = sum(sal)[20, any, any]
9 ,sal[30, null, 'ZZ-Sum'] = sum(sal)[30, any, any]
10 ,sal[null, null, 'ZZ-All'] = sum(sal)[any, any, 'ZZ-Sum']
11 )
12 order by deptno, empno, ename
13 /
DEPTNO EMPNO ENAME SAL
10 7782 CLARK 2450
10 7839 KING 5000
10 7934 MILLER 1300
10 ZZ-Sum 8750
20 7369 SMITH 800
20 7566 JONES 2975
20 7788 SCOTT 3000
20 7876 ADAMS 1100
20 7902 FORD 3000
20 ZZ-Sum 10875
30 7499 ALLEN 1600
30 7521 WARD 1250
30 7654 MARTIN 1250
30 7698 BLAKE 2850
30 7844 TURNER 1500
30 7900 JAMES 950
30 ZZ-Sum 9400
ZZ-All 29025
18 rows selected.Regards
eriMany thanks to you! Your hint shows me, that in this case the model clause is not the right way to go.
The statement below fits exactly my requirements:
SQL> select
2 g.deptno,
3 e.empno,
4 decode(g.grouping_empno,
5 1, decode(g.deptno, null, 'All-Total:', 'Dept-Total:'),
6 e.ename) emp_name,
7 e.job, g.sum_sal salary
8 from (select deptno, empno, grouping(empno) grouping_empno, sum(sal) sum_sal
9 from emp
10 group by rollup(deptno, empno)
11 order by deptno, grouping(empno), empno) g, emp e
12 where g.empno = e.empno (+)
13 /
DEPTNO EMPNO EMP_NAME JOB SALARY
10 7782 CLARK MANAGER 2450
10 7839 KING PRESIDENT 5000
10 7934 MILLER CLERK 1300
10 Dept-Total: 8750
20 7369 SMITH CLERK 800
20 7566 JONES MANAGER 2975
20 7788 SCOTT ANALYST 3000
20 7876 ADAMS CLERK 1100
20 7902 FORD ANALYST 3000
20 Dept-Total: 10875
30 7499 ALLEN SALESMAN 1600
30 7521 WARD SALESMAN 1250
30 7654 MARTIN SALESMAN 1250
30 7698 BLAKE MANAGER 2850
30 7844 TURNER SALESMAN 1500
30 7900 JAMES CLERK 950
30 Dept-Total: 9400
All-Total: 29025
18 rows selected.Regards
eri -
Query help with round up of dates
Hi,
I have a problem with my query.
I am calculating the difference between two dates and I want to get the hours.
The problem is that I want the following to happen:
if the difference is x such that x > 0 it should round it up to 1 (example: x = 0.1 it should be rounded up to 1)
if the difference is y such that y >1 it should be rounded to 1 (example y = 1.05 it should be rounded up to 2)
i have the following query at the momet:
select to_char(arrivaldate,'DD/MM/YYYY hh24:mi:ss') as "ARRIVAL", to_char(departuredate,'DD/MM/YYYY hh24:mi:ss') as "DEPARTURE", round(trunc(mod((departuredate-arrivaldate)*24,24),2)) as duration from stay_log;
thanks.Hi,
Format your code so that the physical appearance of the code gives some hint as to what you're doing, as I did below.
When posting code on this forum, always type {code} tags at the beginning and end of formatted sections.
Do you mean that, instead of 21, you want to use the flightid from the main query?
If so, that's called a "correllated query". The tables in the main query (and their columns) can be reference in the sub-query, like this:
select flightid as "FLIGHT",
select destairport_id
from journey,
flight
where flight.flightid = stay_log.flight_id -- correlated to main query
and flight.journeyid = journey.journeyid
) AS "AIRPORT",
to_char(arrivaldate,'DD/MM/YYYY hh24:mi:ss') as "ARRIVAL",
to_char(departuredate,'DD/MM/YYYY hh24:mi:ss') as "DEPARTURE",
ceil((departuredate-arrivaldate)*24) as "DURATION",
cost as "COST"
from stay_log;Often, people give a table alias to the main query table that is being referenced in the sub-query, as shown below.
That's only required when the table name appears in both FROM-clauses.
select flightid as "FLIGHT",
select destairport_id
from journey,
flight
where flight.flightid = s.flight_id -- table alias s used here
and flight.journeyid = journey.journeyid
) AS "AIRPORT",
to_char(arrivaldate,'DD/MM/YYYY hh24:mi:ss') as "ARRIVAL",
to_char(departuredate,'DD/MM/YYYY hh24:mi:ss') as "DEPARTURE",
ceil((departuredate-arrivaldate)*24) as "DURATION",
cost as "COST"
from stay_log s -- table alias s defined here
; -
I am trying to make a query that will list items and the property names that have been checked from the properties tab, but can't seem to find a way to link them correctly. Anyone ever done it successfully? If so please help on how I can do it.
ThanksHi DaytonHoneycutt,
Check this link.
Item master data - properties tab query
Thanks,
Srujal Patel -
Hi All,
I have 2 tables like below. now i have a requirement which i need to do it in CASE OR DECODE. because i have to implement this logic IN SELECT STATEMENT for a column.
In table T1 if Lang = 1 and State = 'P' then display Lang = 'english' in table T2(which is Lang=2 in table T1) Or else display null.
Can we do this logic using CASE or DECODE? pls help
T1
Lang State
1 P
2 N
T2
Lang Dscr
1 central
2 englishSomething like this ?
SQL> ed
Wrote file afiedt.buf
1 WITH t1 AS (SELECT 1 lang, 'P' STATE FROM DUAL UNION ALL
2 SELECT 2 lang, 'N' STATE FROM DUAL
3 )
4 , t2 AS (SELECT 1 lang, 'central' dscr FROM DUAL UNION ALL
5 SELECT 2 lang, 'english' dscr FROM DUAL
6 )
7 SELECT t1.lang,t1.state,CASE
8 WHEN t1.lang=1 AND t1.state='P'
9 THEN (SELECT t2.lang FROM t2 WHERE dscr='english')
10 ELSE NULL
11 END "lang"
12* FROM t1
SQL> /
LANG S lang
1 P 2
2 N -
Hi,
I have an u201CInventory Controllingu201D InfoCube (Cube 1) and defined queries on this InfoCube, which works fine. The time characteristic u201CFiscal year / periodu201D in this cube is derived from MKPF-BLDAT (Document Date in Document).
And I have another u201CPurchasingu201D InfoCube (Cube 2) and defined queries on this InfoCube, which works also fine. The time characteristic u201CFiscal year / periodu201D in this cube is derived from EKKO- BEDAT (Purchasing Document Date).
Now the requirement is to build a single query which reads few key figures from Cube 1 and other key figures from Cube 2. The time characteristics u201CFiscal year / periodu201D in this query must come from Cube 1. The Characteristic value variable on the time characteristics u201CFiscal year / periodu201D is Mandatory.
The other common characteristics Company code, Material, Plant in the query are available in both Cubes.
I have created a MultiProvider which contains InfoCubes Cube1 and Cube 2. I can assign time characteristics u201CFiscal year / periodu201D only from Cube 1. So I will miss the Key figures from Cube 2.
Both Cube 1 and Cube 2 contain a common characteristic u201CPurchasing Document Numberu201D. So I have tried to define an InfoSet on these Cube 1 and Cube 2. But it is not possible to define an InfoSet on the Inventory Controlling InfoCube.
Any clue to solve this problem?
ThanksHi
You can create one more cube CUBE3 which will take data from both the cubes Cube 1 and Cube 2 based on Purchasing document number. And then create a report on Cube 3.
Navesh -
Binding parameter value pass to VO's query which contain IN clause
Dear All,
This based on "IN" clause of VO's query
ex: Following query contain in a VO
SELECT DISTINCT d.dep_id, d.dep_name, e.emp_name from Department d, Employee e where
d.dep_id = e.dep_id
and e.emp_type IN (:param)
In here query consist with IN clause.
So the problem is how parameter pass to this binding variable. (my binding variable param) ?
my parameter value from IMPL class as --> param = "Manager, CEO, Labor, TeramLeader"
When execute it should be display as following :
SELECT DISTINCT d.dep_id, d.dep_name, e.emp_name from Department d, Employee e where
d.dep_id = e.dep_id
and e.emp_type IN ('Manager', 'CEO', 'Labor', 'TeramLeader')
Thanks if Help on this,
Sagara.Hi,
create a client interface method in viweobjectimpl, somewhat like this
public void executeForBranches(int[] branch_code){
ViewCriteria newVc = createViewCriteria();
ViewCriteriaRow vcr = newVc.createViewCriteriaRow();
StringBuilder sb=new StringBuilder();
for(int bc:branch_code){
if(sb.length()>0){
sb.append(",");
sb.append(bc);
String str="(" + sb.toString() + ")";
//System.err.println("Param = " + str);
vcr.setAttribute("OriginBranch", " IN " + str);
newVc.insertRow(vcr);
applyViewCriteria(newVc);
//System.err.println(getQuery());
executeQuery();
}just dragand drop the clientmethod to your taskflow..
for this you would need to remove the inclause from query
SELECT DISTINCT d.dep_id, d.dep_name, e.emp_name from Department d, Employee e where
d.dep_id = e.dep_id
--and e.emp_type IN (:param)Regards,
Santosh -
I have the privilege of performing a very tedious task.
We have some home grown regular expressions in our company. I now need to expand these regular expressions.
Samples:
a = 0-3
b = Null, 0, 1
Expression: Meaning
1:5: 1,2,3,4,5
1a: 10, 11, 12, 13
1b: 1, 10, 11
1[2,3]ab: 120, 1200, 1201, ....
It get's even more inetersting because there is a possibility of 1[2,3]a.ab
I have created two base queries to aid me in my quest. I am using the SQL MODEL clause to solve this problem. I pretty confident that I should be able to convert evrything into a range and the use one of the MODEL clause listed below.
My only confusion is how do I INCREMENT dynamically. The INCREMENT seems to be a constant in both a FOR and ITERATE statement. I need to figure a way to increment with .01, .1, etc.
Any help will be greatly appreciated.
CODE:
Reference: http://www.sqlsnippets.com/en/topic-11663.html
Objective: Expand a range with ITERATE
WITH t AS
(SELECT '2:4' pt
FROM DUAL
UNION ALL
SELECT '6:9' pt
FROM DUAL)
SELECT pt AS code_expression
-- , KEY
-- , min_key
-- , max_key
, m_1 AS code
FROM t
MODEL
PARTITION BY (pt)
DIMENSION BY ( 0 AS KEY )
MEASURES (
0 AS m_1,
TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
RULES
-- UPSERT
ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
ORDER BY pt, m_1
Explanation:
Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
If you need detailed information regarding the MODEL clause please refer to
the Refrence site stated above or read some documentation.
Partition-
Line 18: PARTITION BY (pt)
This will make sure that each "KEY" will start at 0 for each value of pt.
Dimension-
Line 19: DIMENSION BY ( 0 AS KEY )
This is necessary for the refrences max_key[0], and min_key[0] to work.
Measures-
Line 21: 0 AS m_1
A space holder for new values.
Line 22: TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
The result is '1' for '1:5'.
Line 23: TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
The result is '5' for '1:5'.
Rules-
Line 26: UPSERT
This makes it possible for new rows to be created.
Line 27: ITERATE (100000) UNTIL ( ITERATION_NUMBER = max_key[0] - min_key[0] )
This reads ITERATE 100000 times or UNTIL the ITERATION_NUMBER = max_key[0] - min_key[0]
which would be 4 for '1:5', but since the ITERATION_NUMBER starts at 0, whatever follows
is repaeted 5 times.
Line 29: m_1[ITERATION_NUMBER] = min_key[0] + ITERATION_NUMBER
m_1[ITERATION_NUMBER] means m_1[Value of Dimension KEY].
Thus for each row of KEY the m_1 is min_key[0] + ITERATION_NUMBER.
Reference: http://www.sqlsnippets.com/en/topic-11663.html
Objective: Expand a range using FOR
WITH t AS
(SELECT '2:4' pt
FROM DUAL
UNION ALL
SELECT '6:9' pt
FROM DUAL)
, base AS
SELECT pt AS code_expression
, KEY AS code
, min_key
, max_key
, my_increment
, m_1
FROM t
MODEL
PARTITION BY (pt)
DIMENSION BY ( CAST(0 AS NUMBER) AS KEY )
MEASURES (
CAST(NULL AS CHAR) AS m_1,
TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key,
TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key,
.1 AS my_increment
RULES
-- UPSERT
m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
ORDER BY pt, KEY, m_1
SELECT code_expression, code
FROM base
WHERE m_1 = 'Y'
Explanation:
Line numbers are based on the assupmtion that "WITH t AS" starts at line 5.
If you need detailed information regarding the MODEL clause please refer to
the Refrence site stated above or read some documentation.
Partition-
Line 21: PARTITION BY (pt)
This will make sure that each "KEY" will start at 0 for each value of pt.
Dimension-
Line 22: DIMENSION BY ( 0 AS KEY )
This is necessary for the refrences max_key[0], and min_key[0] to work.
Measures-
Line 24: CAST(NULL AS CHAR) AS m_1
A space holder for results.
Line 25: TO_NUMBER(SUBSTR(pt, 1, INSTR(pt, ':') - 1)) AS min_key
The result is '1' for '1:5'.
Line 26: TO_NUMBER(SUBSTR(pt, INSTR(pt, ':') + 1)) AS max_key
The result is '5' for '1:5'.
Line 27: .1 AS my_increment
The INCREMENT I would like to use.
Rules-
Line 30: UPSERT
This makes it possible for new rows to be created.
However seems like it is not necessary.
Line 32: m_1[FOR KEY FROM min_key[0] TO max_key[0] INCREMENT 1] = 'Y'
Where the KE value is between min_key[0] and max_key[0] set the value of m_1 to 'Y'
*/Of course, you can accomplish the same thing without MODEL using an Integer Series Generator like this.
create table t ( min_val number, max_val number, increment_size number );
insert into t values ( 2, 3, 0.1 );
insert into t values ( 1.02, 1.08, 0.02 );
commit;
create table integer_table as
select rownum - 1 as n from all_objects where rownum <= 100 ;
select
min_val ,
increment_size ,
min_val + (increment_size * n) as val
from t, integer_table
where
n between 0 and ((max_val - min_val)/increment_size)
order by 3
MIN_VAL INCREMENT_SIZE VAL
1.02 .02 1.02
1.02 .02 1.04
1.02 .02 1.06
1.02 .02 1.08
2 .1 2
2 .1 2.1
2 .1 2.2
2 .1 2.3
2 .1 2.4
2 .1 2.5
2 .1 2.6
2 .1 2.7
2 .1 2.8
2 .1 2.9
2 .1 3
15 rows selected.--
Joe Fuda
http://www.sqlsnippets.com/ -
Need help with writing a query with dynamic FROM clause
Hi Folks,
I need help with an query that should generate the "FROM" clause dynamically.
My main query is as follows
select DT_SKEY, count(*)
from *???*
where DT_SKEY between 20110601 and 20110719
group by DT_SKEY
having count(*) = 0
order by 1; The "from" clause of the above query should be generated as below
select 'Schema_Name'||'.'||TABLE_NAME
from dba_tables
where OWNER = 'Schema_Name'Simply sticking the later query in the first query does not work.
Any pointers will be appreciated.
Thanks
rogers42Hi,
rogers42 wrote:
Hi Folks,
I need help with an query that should generate the "FROM" clause dynamically.
My main query is as follows
select DT_SKEY, count(*)
from *???*
where DT_SKEY between 20110601 and 20110719
group by DT_SKEY
having count(*) = 0
order by 1; The "from" clause of the above query should be generated as below
select 'Schema_Name'||'.'||TABLE_NAME
from dba_tables
where OWNER = 'Schema_Name'
Remember that anything inside quotes is case-sensitive. Is the owner really "Schema_Name" with a capital S and a capital N, and 8 lower-case letters?
Simply sticking the later query in the first query does not work.Right; the table name must be given when you compile the query. It's not an expression that you can generate in the query itself.
Any pointers will be appreciated.In SQL*Plus, you can do something like the query bleow.
Say you want to count the rows in scott.emp, but you're not certain that the name is emp; it could be emp_2011 or emp_august, or anything else that starts with e. (And the name could change every day, so you can't just look it up now and hard-code it in a query that you want to run in the future.)
Typically, how dynamic SQL works is that some code (such as a preliminary query) gets some of the information you need to write the query first, and you use that information in a SQL statement that is compiled and run after that. For example:
-- Preliminary Query:
COLUMN my_table_name_col NEW_VALUE my_table_name
SELECT table_name AS my_table_name_col
FROM all_tables
WHERE owner = 'SCOTT'
AND table_name LIKE 'E%';
-- Main Query:
SELECT COUNT (*) AS cnt
FROM scott.&my_table_name
;This assumes that the preliminary query will find exactly one row; that is, it assumes that SCOTT has exactly one table whose name starts with E. Could you have 0 tables in the schema, or more than 1? If so, what results would you want? Give a concrete example, preferably suing commonly available tables (like those in the SCOTT schema) so that the poepl who want to help you can re-create the problem and test their ideas.
Edited by: Frank Kulash on Aug 11, 2011 2:30 PM -
[10g] Need help with order by clause in hierarchical query
I have the following sample data:
CREATE TABLE bill_test1
( parent_part CHAR(25)
, child_part CHAR(25)
, line_nbr NUMBER(5)
, qty_per NUMBER(9,5)
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-10',100,1);
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-20',200,2);
INSERT INTO bill_test1 VALUES ('ABC-1','ABC-30',300,3);
INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-1',401,10);
INSERT INTO bill_test1 VALUES ('ABC-1','HARDWARE-2',402,5);
INSERT INTO bill_test1 VALUES ('ABC-10','ABC-155',100,2);
INSERT INTO bill_test1 VALUES ('ABC-10','HARDWARE-1',200,1);
INSERT INTO bill_test1 VALUES ('ABC-155','RAW-2',100,4.8);
INSERT INTO bill_test1 VALUES ('ABC-155','HARDWARE-3',200,3);
INSERT INTO bill_test1 VALUES ('ABC-20','RAW-1',100,10.2);
INSERT INTO bill_test1 VALUES ('ABC-30','RAW-3',100,3);And the query below gives me exactly what I want, in the order I want it. However, I am wondering if there is a way to get this order without creating the SEQ column, since I don't need it in my results
SELECT part_nbr
, parent_part
, child_part
FROM (
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
, dual
CONNECT BY parent_part = PRIOR child_part
WHERE part_nbr = 'ABC-1'
ORDER BY seq
Results of above query, except with SEQ included in SELECT (just to show what I'm sorting off of):
PART_NBR PARENT_PART CHILD_PART SEQ
ABC-1 ABC-1 ABC-10 100
ABC-1 ABC-10 ABC-155 100 100
ABC-1 ABC-155 RAW-2 100 100 100
ABC-1 ABC-155 HARDWARE-3 100 100 200
ABC-1 ABC-10 HARDWARE-1 100 200
ABC-1 ABC-1 ABC-20 200
ABC-1 ABC-20 RAW-1 200 100
ABC-1 ABC-1 ABC-30 300
ABC-1 ABC-30 RAW-3 300 100
ABC-1 ABC-1 HARDWARE-1 401
ABC-1 ABC-1 HARDWARE-2 402Hi,
As long as there's only one root, you can say ORDER SIBLINGS BY, but you can't do that in a sub-query (well, you can, but usually there's no point in doing it in a sub-query). If the CONNECT BY is being done in a sub-query, there is no guarantee that the main query will preserve the hierarchical order that the sub-query provides.
The query you posted doesn't require a suib-query, so you can say:
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
--, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
WHERE CONNECT_BY_ROOT b.parent_part = 'ABC-1'
CONNECT BY parent_part = PRIOR child_part
ORDER SIBLINGS BY b.line_nbr
;I said the query you posted doesn't require a sub-query. It also doesn't require dual, so I suspect what you posted is a simplification of what you're really doing, and that may need a sub-query. In particular, if you intend to GROUP BY part_nbr, then you need the sub-query. We can repeat the CONNECT_BY_ROOT expression in the WHERE clause (or, now that I think about it, use a START WITH clause instead of WHERE), but, for some reason, we can't use CONNECT_BY_ROOT in a GROUP BY clause; we need to compute CONNECT_BY_ROOT in a sub-query, give it a name (like part_nbr), and GROUP BY that column in a super-query.
This assumes that there is only one root node. ORDER SIBLINGS BY means just that: children of a common parent will appear in order, but the root nodes, who have no parents, will not necessarily be in order.
Here's what I meant by using START WITH instead of WHERE:
SELECT CONNECT_BY_ROOT b.parent_part AS part_nbr
, b.parent_part
, b.child_part
--, SYS_CONNECT_BY_PATH(b.line_nbr,' ') AS seq
FROM bill_test1 b
START WITH b.parent_part = 'ABC-1'
CONNECT BY parent_part = PRIOR child_part
ORDER SIBLINGS BY b.line_nbr
;This should be much more efficient, because it narrows down the results before you waste time getting their descendants.
Using a START WITH clause here is analagous to me sending you an e-mail, saying "Come to a meeting a my office at 3:00."
Using a WHERE clause here is analagous to me sending an e-mail to everyone in the company, saying "Come to a meeting a my office at 3:00", and then, as people get here, telling everyone except you that they can go back.
ORDER SIBLINGS BY was introduced in Oracle 9.
Edited by: Frank Kulash on Dec 9, 2010 2:39 PM
Added version with START WITH clause -
SQL Query help ( On connect By level clause)
Hi all,
I have this query developed with data in with clause.
With dat As
select '@AAA @SSS @DDD' col1 from dual union all
select '@ZZZ @XXX @TTT @RRR @ZZA' col1 from dual
Select regexp_substr( col1 , '[^@][A-Z]+',1,level) Show from dat
connect by level <= regexp_count(col1, '@');Current output :-
SHOW
AAA
SSS
DDD
RRR
ZZA
TTT
RRR
ZZA
XXX
DDD
RRR
SHOW
ZZA
TTT
RRR
ZZA
. . .1st row comes fine, But next row data is getting duplicated. And total record count = 30. I tried with some but didn't work.
Expected output :-
SHOW
AAA
SSS
DDD
ZZZ
XXX
TTT
RRR
ZZAI need some change on my query and I am not able to find that. So anybody can add on that or can also provide some different solution too.
Thanks!
AshutoshHi,
When you use something like "CONNECT BY LEVEL <= x", then at least one of the following must be true:
(a) the table has no more than 1 row
(b) there are other conditions in the CONNECT BY clause, or
(c) you know what you are doing.
To help see why, run this query
SELECT SYS_CONNECT_BY_PATH (dname, '/') AS path
, LEVEL
FROM scott.dept
CONNECT BY LEVEL <= 3
;and study the results:
PATH LEVEL
/ACCOUNTING 1
/ACCOUNTING/ACCOUNTING 2
/ACCOUNTING/ACCOUNTING/ACCOUNTING 3
/ACCOUNTING/ACCOUNTING/RESEARCH 3
/ACCOUNTING/ACCOUNTING/SALES 3
/ACCOUNTING/ACCOUNTING/OPERATIONS 3
/ACCOUNTING/RESEARCH 2
/ACCOUNTING/RESEARCH/ACCOUNTING 3
/ACCOUNTING/RESEARCH/RESEARCH 3
/ACCOUNTING/RESEARCH/SALES 3
/ACCOUNTING/RESEARCH/OPERATIONS 3
/ACCOUNTING/SALES 2
/ACCOUNTING/SALES/ACCOUNTING 3
84 rows selected. -
Bin fitting with a counter using both analytics and model clause.
11.2.0.3
This falls under 'just want to figure out how to do it'. Its not critical for work. I want to try to see if its possible to do this with both analytic function and with a model clause. Just to see if its possible. It has been stumping me.
I got the idea to look at this from this article about bin fitting. I have been playing with the model clause and I think you would do something with the 'increment' clause, but I dont see a way to reset it to 1 at a certain point.
http://www.oracle.com/technetwork/issue-archive/2012/12-mar/o22asktom-1518271.html
The case I want to look at is, bin fitting based on a counter and a partition by. In theory this should be simpler than the example in the link.
[code]
create table myrooms (
room_number number,
person_id number);
create unique index myrooms_ind on myrooms(room_number,person_id);
[/code]
Person_id is not unique. So row_number is more appropriate than rank or dense_rank.
Problem: Partition by room_number, assign up to 50 people to a specific group with in the same room. This seems like it could be handled with a row_number() and a window clause, but that is not supported.
I need to basically translate the old procedural counter into sql:
pseudo-code that does not compile that would have a reason to use this logic.
[code]
declare
cursor curGetRoom
select room_number,person_id
from my rooms
order by room_number;
counter number := 1;
vCurrentRoom myroom.room_number%type;
begin
for i in curGetRoom loop
if vCurrentRoom is null then
vCurrentRoom := i.room_number;
elsif vCurrentRoom = i.room_number then
if counter < 51 then counter :=counter+1;
else counter := 1;
else
vCurrentRoom := i.room_number;
counter :=1;
end if;
end;
[/code]
simple partition query., but I dont see a way to limit this to 50 and then start over. Window functions are not supported with row_number()
[code]
select room_number,person_id,row_number() over (partition by room_number order by person_id) rn
from myrooms
[/code]11.2.0.3
This falls under 'just want to figure out how to do it'. Its not critical for work. I want to try to see if its possible to do this with both analytic function and with a model clause. Just to see if its possible. It has been stumping me.
I got the idea to look at this from this article about bin fitting. I have been playing with the model clause and I think you would do something with the 'increment' clause, but I dont see a way to reset it to 1 at a certain point.
http://www.oracle.com/technetwork/issue-archive/2012/12-mar/o22asktom-1518271.html
The case I want to look at is, bin fitting based on a counter and a partition by. In theory this should be simpler than the example in the link.
[code]
create table myrooms (
room_number number,
person_id number);
create unique index myrooms_ind on myrooms(room_number,person_id);
[/code]
Person_id is not unique. So row_number is more appropriate than rank or dense_rank.
Problem: Partition by room_number, assign up to 50 people to a specific group with in the same room. This seems like it could be handled with a row_number() and a window clause, but that is not supported.
I need to basically translate the old procedural counter into sql:
pseudo-code that does not compile that would have a reason to use this logic.
[code]
declare
cursor curGetRoom
select room_number,person_id
from my rooms
order by room_number;
counter number := 1;
vCurrentRoom myroom.room_number%type;
begin
for i in curGetRoom loop
if vCurrentRoom is null then
vCurrentRoom := i.room_number;
elsif vCurrentRoom = i.room_number then
if counter < 51 then counter :=counter+1;
else counter := 1;
else
vCurrentRoom := i.room_number;
counter :=1;
end if;
end;
[/code]
simple partition query., but I dont see a way to limit this to 50 and then start over. Window functions are not supported with row_number()
[code]
select room_number,person_id,row_number() over (partition by room_number order by person_id) rn
from myrooms
[/code]
Maybe you are looking for
-
DMS Document not getting created thru Webdynpro ABAP Strange Problem
Dear all, My requirement is that I have a Webdynpro ABAP application sitting on SAP Server1 and I am having a FileUploadUI Element in there for uploading files and we have SAP Server2 with the DMS configured. So, what we have done is we have an RFC i
-
Initial Load Error - No generation performed. Call transaction GN_START
Hi Folks, We are doing middleware configuration for data migration between R3->CRM.Have followed "Best Practies" configuration Guide. System Using; CRM 2007 and ECC6.0 Issue While performing initial load, system is throwing the error as 001- No gener
-
Using my Personal Domain Name on a trial version of .Mac?
Okay, I have a trial version of .mac, and am very happy with it. I used Iweb to build a good website for my artwork, and I'm all set to publish. But I want to put my registered domain name to my new site, so when you type the simple domain name (ex:
-
Limit of attached documents to the PO
Hello experts! I have a question about the purchase orders. I have seen that it is possible to attach a document to a purchase order, but how many documents could I attach to the PO? and what is the limit of these documents? And if I attach a documen
-
When I try to add an e-book I get an "error check activation" message and the book wont add why?