UNION SQL QUERY
Hello
i have problem in sql query
there two queries
the first
SELECT m.segment1
|| '.'
|| m.segment2
|| '.'
|| m.segment3
|| '.'
|| m.segment4
|| '.'
|| m.segment5
|| '.'
|| m.segment6 ACCOUNT,q.description,
NVL ((SUM (l.entered_dr) - SUM (l.entered_cr)),
SUM (l.entered_dr)
) debt,
NVL (NULL, 0) credit
FROM gl_code_combinations m,
gl_je_batches c,
gl_je_categories n,
gl_je_headers h,
gl_je_lines l,
gl_sets_of_books t,
fnd_flex_values_vl q
WHERE m.segment1 || '.' || m.segment2 || '.' || m.segment3
BETWEEN NVL (SUBSTR (:account_from, 1, 9),
m.segment1 || '.' || m.segment2 || '.' || m.segment3
AND NVL (SUBSTR (:account_to, 1, 9),
m.segment1 || '.' || m.segment2 || '.' || m.segment3
AND m.segment4 || '.' || m.segment5 || '.' || m.segment6
BETWEEN NVL (SUBSTR (:account_from, 11, 23),
m.segment4 || '.' || m.segment5 || '.' || m.segment6
AND NVL (SUBSTR (:account_to, 11, 23),
segment4 || '.' || segment5 || '.' || segment6
AND h.default_effective_date BETWEEN :from_date AND :TO_DATE
AND n.user_je_category_name = NVL (:cate, n.user_je_category_name)
AND m.chart_of_accounts_id = :chartid
AND q.flex_value = m.segment5
AND q.parent_flex_value_low = m.segment4
AND q.flex_value_set_id = 1009648
AND h.je_header_id = l.je_header_id
AND h.je_batch_id = c.je_batch_id
AND l.code_combination_id = m.code_combination_id
AND m.chart_of_accounts_id = t.chart_of_accounts_id
AND l.set_of_books_id = t.set_of_books_id
AND h.je_category = n.je_category_name
AND ( n.user_je_category_name LIKE 'PAS_%'
OR n.user_je_category_name LIKE 'BS_%'
OR n.user_je_category_name LIKE 'MS_%'
OR n.user_je_category_name LIKE 'PS_%'
OR n.user_je_category_name LIKE 'TY_%'
OR n.user_je_category_name LIKE 'VEH_%'
OR n.user_je_category_name LIKE 'WS_%'
GROUP BY m.segment1
|| '.'
|| m.segment2
|| '.'
|| m.segment3
|| '.'
|| m.segment4
|| '.'
|| m.segment5
|| '.'
|| m.segment6,
q.description,
M.CODE_COMBINATION_ID
and this query return 13 rows
the second query is
select
m.segment1
|| '.'
|| m.segment2
|| '.'
|| m.segment3
|| '.'
|| m.segment4
|| '.'
|| m.segment5
|| '.'
|| m.segment6 ACCOUNT,q.description,NVL (null,0) Debit,NVL(SUM(l.ENTERED_CR ),0)Credit
from gl_code_combinations M,
gl_je_batches c,
gl_je_categories N,
GL_JE_HEADERS H,
GL_JE_LINES L,
GL_SETS_OF_BOOKS T,
fnd_flex_values_vl q
where M.segment1 || '.' || M.segment2 || '.' ||M.segment3
BETWEEN NVL (SUBSTR (:ACCOUNT_FROM, 1, 9),
M.segment1 || '.' ||M.segment2 || '.' || M.segment3
AND NVL (SUBSTR (:ACCOUNT_TO, 1, 9),
M.segment1 || '.' || M.segment2 || '.' ||M.segment3
AND M.segment4 || '.' ||M.segment5 || '.' || M.segment6
BETWEEN NVL (SUBSTR(:ACCOUNT_FROM, 11, 23),
M. segment4 || '.' ||M.segment5 || '.' || M.segment6
AND NVL (SUBSTR (:ACCOUNT_TO, 11, 23),
segment4 || '.' || segment5 || '.' || segment6
AND H.DEFAULT_EFFECTIVE_DATE BETWEEN :FROM_DATE AND :TO_DATE
AND N.user_je_category_name=NVL(:CATE,N.user_je_category_name)
AND q.flex_value = m.segment5
AND q.parent_flex_value_low = m.segment4
AND q.flex_value_set_id = 1009648
AND M.CHART_OF_ACCOUNTS_ID=:CHARTID
AND H.JE_HEADER_ID=L.JE_HEADER_ID
AND H.JE_BATCH_ID=C.JE_BATCH_ID
AND L.CODE_COMBINATION_ID=M.CODE_COMBINATION_ID
AND M.CHART_OF_ACCOUNTS_ID=T.CHART_OF_ACCOUNTS_ID
AND L.SET_OF_BOOKS_ID=T.SET_OF_BOOKS_ID
AND H.JE_CATEGORY=N.JE_CATEGORY_NAME
AND (N.user_je_category_name NOT LIKE 'PAS_%'AND N.user_je_category_name NOT LIKE 'BS_%'
AND N.user_je_category_name NOT LIKE 'MS_%' AND N.user_je_category_name NOT LIKE 'PS_%'
AND N.user_je_category_name NOT LIKE 'TY_%' AND N.user_je_category_name NOT LIKE 'VEH_%'
AND N.user_je_category_name NOT LIKE 'WS_%'
OR N.user_je_category_name LIKE 'RE_%')
GROUP BY m.segment1
|| '.'
|| m.segment2
|| '.'
|| m.segment3
|| '.'
|| m.segment4
|| '.'
|| m.segment5
|| '.'
|| m.segment6 ,
q.description
and return 12 rows
i want to union this querys
can any programmer help me
thank
What the problem in that? I dont get it. You can just use UNION ALL.
SELECT m.segment1
|| '.'
|| m.segment2
|| '.'
|| m.segment3
|| '.'
|| m.segment4
|| '.'
|| m.segment5
|| '.'
|| m.segment6 ACCOUNT,q.description,
NVL ((SUM (l.entered_dr) - SUM (l.entered_cr)),
SUM (l.entered_dr)
) debt,
NVL (NULL, 0) credit
FROM gl_code_combinations m,
gl_je_batches c,
gl_je_categories n,
gl_je_headers h,
gl_je_lines l,
gl_sets_of_books t,
fnd_flex_values_vl q
WHERE m.segment1 || '.' || m.segment2 || '.' || m.segment3
BETWEEN NVL (SUBSTR (:account_from, 1, 9),
m.segment1 || '.' || m.segment2 || '.' || m.segment3
AND NVL (SUBSTR (:account_to, 1, 9),
m.segment1 || '.' || m.segment2 || '.' || m.segment3
AND m.segment4 || '.' || m.segment5 || '.' || m.segment6
BETWEEN NVL (SUBSTR (:account_from, 11, 23),
m.segment4 || '.' || m.segment5 || '.' || m.segment6
AND NVL (SUBSTR (:account_to, 11, 23),
segment4 || '.' || segment5 || '.' || segment6
AND h.default_effective_date BETWEEN :from_date AND :TO_DATE
AND n.user_je_category_name = NVL (:cate, n.user_je_category_name)
AND m.chart_of_accounts_id = :chartid
AND q.flex_value = m.segment5
AND q.parent_flex_value_low = m.segment4
AND q.flex_value_set_id = 1009648
AND h.je_header_id = l.je_header_id
AND h.je_batch_id = c.je_batch_id
AND l.code_combination_id = m.code_combination_id
AND m.chart_of_accounts_id = t.chart_of_accounts_id
AND l.set_of_books_id = t.set_of_books_id
AND h.je_category = n.je_category_name
AND ( n.user_je_category_name LIKE 'PAS_%'
OR n.user_je_category_name LIKE 'BS_%'
OR n.user_je_category_name LIKE 'MS_%'
OR n.user_je_category_name LIKE 'PS_%'
OR n.user_je_category_name LIKE 'TY_%'
OR n.user_je_category_name LIKE 'VEH_%'
OR n.user_je_category_name LIKE 'WS_%'
GROUP BY m.segment1
|| '.'
|| m.segment2
|| '.'
|| m.segment3
|| '.'
|| m.segment4
|| '.'
|| m.segment5
|| '.'
|| m.segment6,
q.description,
M.CODE_COMBINATION_ID
union all
select
m.segment1
|| '.'
|| m.segment2
|| '.'
|| m.segment3
|| '.'
|| m.segment4
|| '.'
|| m.segment5
|| '.'
|| m.segment6 ACCOUNT,q.description,NVL (null,0) Debit,NVL(SUM(l.ENTERED_CR ),0)Credit
from gl_code_combinations M,
gl_je_batches c,
gl_je_categories N,
GL_JE_HEADERS H,
GL_JE_LINES L,
GL_SETS_OF_BOOKS T,
fnd_flex_values_vl q
where M.segment1 || '.' || M.segment2 || '.' ||M.segment3
BETWEEN NVL (SUBSTR (:ACCOUNT_FROM, 1, 9),
M.segment1 || '.' ||M.segment2 || '.' || M.segment3
AND NVL (SUBSTR (:ACCOUNT_TO, 1, 9),
M.segment1 || '.' || M.segment2 || '.' ||M.segment3
AND M.segment4 || '.' ||M.segment5 || '.' || M.segment6
BETWEEN NVL (SUBSTR(:ACCOUNT_FROM, 11, 23),
M. segment4 || '.' ||M.segment5 || '.' || M.segment6
AND NVL (SUBSTR (:ACCOUNT_TO, 11, 23),
segment4 || '.' || segment5 || '.' || segment6
AND H.DEFAULT_EFFECTIVE_DATE BETWEEN :FROM_DATE AND :TO_DATE
AND N.user_je_category_name=NVL(:CATE,N.user_je_category_name)
AND q.flex_value = m.segment5
AND q.parent_flex_value_low = m.segment4
AND q.flex_value_set_id = 1009648
AND M.CHART_OF_ACCOUNTS_ID=:CHARTID
AND H.JE_HEADER_ID=L.JE_HEADER_ID
AND H.JE_BATCH_ID=C.JE_BATCH_ID
AND L.CODE_COMBINATION_ID=M.CODE_COMBINATION_ID
AND M.CHART_OF_ACCOUNTS_ID=T.CHART_OF_ACCOUNTS_ID
AND L.SET_OF_BOOKS_ID=T.SET_OF_BOOKS_ID
AND H.JE_CATEGORY=N.JE_CATEGORY_NAME
AND (N.user_je_category_name NOT LIKE 'PAS_%'AND N.user_je_category_name NOT LIKE 'BS_%'
AND N.user_je_category_name NOT LIKE 'MS_%' AND N.user_je_category_name NOT LIKE 'PS_%'
AND N.user_je_category_name NOT LIKE 'TY_%' AND N.user_je_category_name NOT LIKE 'VEH_%'
AND N.user_je_category_name NOT LIKE 'WS_%'
OR N.user_je_category_name LIKE 'RE_%')
GROUP BY m.segment1
|| '.'
|| m.segment2
|| '.'
|| m.segment3
|| '.'
|| m.segment4
|| '.'
|| m.segment5
|| '.'
|| m.segment6 ,
q.description
Similar Messages
-
Sql query to get union of matching rows
I want to write a sql query that shows union f all the [Type] for each [Key] if [Key] has atleast one [Type] in common and for non matched [Key]s it will return the row as it is.
For example In the sql table below [Key] '1' and '2' has [Type] 'B' in common and [Key] '1' and '4' has [Type] 'A' in common. In this case [Key] '1', '2' and '4' are related so result will be union of [Type]s in [Key]s '1', '2' and '4' which are 'A', 'B', 'C'
and 'E' for each [Key]. And [Key] '3' has no [Type] in common so it will return itself.
Input:
declare @categories table ([Key] int, [Type] Char(1))
insert into @categories ([Key], [Type]) values (1, 'A')
insert into @categories ([Key], [Type]) values (1, 'B')
insert into @categories ([Key], [Type]) values (2, 'B')
insert into @categories ([Key], [Type]) values (2, 'C')
insert into @categories ([Key], [Type]) values (3, 'D')
insert into @categories ([Key], [Type]) values (4, 'E')
insert into @categories ([Key], [Type]) values (4, 'A')
insert into @categories ([Key], [Type]) values (5, 'F')
insert into @categories ([Key], [Type]) values (5, 'G')
insert into @categories ([Key], [Type]) values (6, 'G')
insert into @categories ([Key], [Type]) values (6, 'H')
Desired output:
Key Type
1 A
1 B
1 C
1 E
2 A
2 B
2 C
3 D
4 A
4 B
4 E
5 F
5 G
5 H
6 F
6 G
6 H
The data element names are wrong. KEY is a reserved word; “Categories" and "type" are called attribute properties in ISO-11179 rules. Matthias Kläy is right; this is a graph problem in disguise, but you can do it with set theory to get what are called
equivalence classes.
An edge in a graph has two nodes. Some authors allow a single node to count as a edge, but a better way is to put the same node on both ends of the edge. Here is the graph in a table with all the needed constraints. This is why you should post DDL and not be
so rude.
DROP TABLE Graph;
CREATE TABLE Graph
(edge INTEGER NOT NULL,
node_1 CHAR(1) NOT NULL,
node_2 CHAR(1) NOT NULL,
CHECK (node_1 <= node_2),
PRIMARY KEY (node_1, node_2));
Here is your data in the correct format.
INSERT INTO Graph
VALUES
(1, 'A', 'B'),
(2, 'B', 'C'),
(3, 'D', 'D'), -- orphan node
(4, 'A', 'E'),
(5, 'F', 'G'),
(6, 'G', 'H');
Now Google Warshall's Algorithm. It uses three nested loops and an adjacency array. This is very clean and fast in a procedural language. Not so much in SQL. Let us do this in steps:
WITH X1 (edge, node1_1, node1_2, node2_1, node2_2 )
AS
(SELECT CASE WHEN G1.edge <> G2.edge
THEN G1.edge ELSE G2.edge END,
G1.node_1, G1.node_2,
G2.node_1, G2.node_2
FROM Graph AS G1, Graph AS G2
WHERE G1.node_1 IN (G2.node_1, G2.node_2)
AND G1.edge <> G2.edge),
X2 (edge, node_1, node_2)
AS
(SELECT edge,
CASE WHEN node1_1 IN (node2_1, node2_2) THEN node1_2 ELSE node1_1 END,
CASE WHEN node2_1 IN (node1_1, node1_2) THEN node2_2 ELSE node2_1 END
FROM X1)
SELECT DISTINCT edge,
CASE WHEN node_1 < node_2 THEN node_1 ELSE node_2 END,
CASE WHEN node_2 < node_1 THEN node_1 ELSE node_2 END
FROM X2;
The X1 subquery gets the paths of length two. The X2 subquery removes the middle node and creates a new sorted edge. Insert these new rows into Graphs, if they are not there. Repeat the process until no more rows are added.
DROP TABLE Graph;
CREATE TABLE Graph
(edge INTEGER NOT NULL,
node_1 CHAR(1) NOT NULL,
node_2 CHAR(1) NOT NULL,
CHECK (node_1 <= node_2),
PRIMARY KEY (node_1, node_2));
INSERT INTO Graph
VALUES
(1, 'A', 'B'),
(2, 'B', 'C'),
(3, 'D', 'D'), -- orphan node
(4, 'A', 'E'),
(5, 'F', 'G'),
(6, 'G', 'H');
Here is the monster rolled up into a single statement.
INSERT INTO Graph
SELECT DISTINCT edge,
CASE WHEN node_1 < node_2 THEN node_1 ELSE node_2 END,
CASE WHEN node_2 < node_1 THEN node_1 ELSE node_2 END
FROM (SELECT edge,
CASE WHEN node1_1 IN (node2_1, node2_2) THEN node1_2 ELSE node1_1 END,
CASE WHEN node2_1 IN (node1_1, node1_2) THEN node2_2 ELSE node2_1 END
FROM
(SELECT CASE WHEN G1.edge < G2.edge
THEN G1.edge ELSE G2.edge END,
G1.node_1, G1.node_2,
G2.node_1, G2.node_2
FROM Graph AS G1, Graph AS G2
WHERE G1.node_1 IN (G2.node_1, G2.node_2)
AND G1.edge <> G2.edge) AS X1(edge,node1_1, node1_2, node2_1, node2_2) )
AS X2(edge, node_1, node_2)
EXCEPT
SELECT * FROM Graph;
SELECT * FROM Graph ORDER BY edge, node_1, node_2;
1 A B
1 A C
1 B E
1 C E
2 B C
3 D D
4 A E
5 F G
5 F H
6 G H
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Hi,
i have a problem with my sql query.
I need the difference from query 2 - query 1.
the red marked row should be ignored because its already in table 1.
Union compares all colums not just the first 3.
Here's a screen of the problem:
http://c60.img-up.net/?up=screenoracskt6.JPG
thx for allHi,
Welcome to the forum!
Whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
Explain how you get those results from that data.
Always say what version of oracle you're using.
user6754335 wrote:
Hi,
i have a problem with my sql query.
I need the difference from query 2 - query 1.
the red marked row should be ignored because its already in table 1.
Union compares all colums not just the first 3.That's right; UNION compare all the columns selected. If you're only interested in 3 of the columns, then only select those 3.
If you need to display more columns, but not where all 3 of them match, then the best way is probably an outer join; but there are lots of other ways, including NOT EXISTS, NOT IN, and MINUS (in a sub-query).
Here's a screen of the problem:
http://c60.img-up.net/?up=screenoracskt6.JPG
Post anything relevant on this site. -
Need sql query to remove duplicates using UNION ALL clause
Hi,
I have a sql query which has UNION clause.But the UNION clause is causing some performance issues.
To overcome that I have used UNION ALL to improve performance but its returning duplicates.
Kindly anyone send a sample SQL query where my primary objective is used to use UNION ALL clause and to consider unique rows (elimating duplicate
ones)
Any help will be needful for me
Thanks and Regardswhy not UNION? :(
another way also use MINUS
SQL>
SQL> with t as
2 (
3 select 1 if from dual union all
4 select 2 if from dual union all
5 select 1 if from dual union all
6 select 3 if from dual union all
7 select 3 if from dual
8 )
9 ,t2 as
10 (
11 select 1 if from dual union all
12 select 2 if from dual union all
13 select 3 if from dual union all
14 select 4 if from dual union all
15 select 5 if from dual
16 )
17 (select if from t
18 union all
19 select if from t2)
20 /
IF
1
2
1
3
3
1
2
3
4
5
10 rows selected
SQL> so
SQL>
SQL> with t as
2 (
3 select 1 if from dual union all
4 select 2 if from dual union all
5 select 1 if from dual union all
6 select 3 if from dual union all
7 select 3 if from dual
8 )
9 ,t2 as
10 (
11 select 1 if from dual union all
12 select 2 if from dual union all
13 select 3 if from dual union all
14 select 4 if from dual union all
15 select 5 if from dual
16 )
17 (select if from t
18 union all
19 select if from t2)
20 minus
21 select -99 from dual
22 /
IF
1
2
3
4
5
SQL> -
How to get resultset from procedure having dynamic select sql query ?
Hi,
I have created a procedure, in which there is dynamic select query. The procedure has one out put parameter which gives error code. When I compile that procedure it compiles successufully. When I run it it executes successfully and gives output error code. But I don't know how to get resultset of that dynamic select sql query. I need that.
This is the procedure:
create or replace
PROCEDURE uspGetProductDetailsMultiOrder
v_DefinitionDBName IN VARCHAR2,
v_CommonDBName IN VARCHAR2,
v_Filter_FilledStatus IN VARCHAR2,
v_Filter_Internal_Counterparty IN nvarchar2,
v_Filter_NoteType IN nvarchar2,
v_Filter_Exchange IN nvarchar2,
v_Filter_Issuer IN nvarchar2,
v_Filter_Product_Category IN VARCHAR2,
v_DateToFilter IN VARCHAR2,
v_Filter_FromDate IN VARCHAR2,
v_Filter_ToDate IN VARCHAR2,
v_Active_YN_Flag IN NVARCHAR2,
v_Entity_ID IN NVARCHAR2,
v_ErrorNumber OUT NUMBER
as
v_SelectSQL nvarchar2(32767);
v_Setting_Name nvarchar2(32767);
v_Default_Value nvarchar2(32767);
v_Config_Value nvarchar2(32767);
v_CCY_ID NUMBER(10,0);
v_CCY_Data nvarchar2(32767);
v_CCY_List nvarchar2(32767);
v_Seq_Id NUMBER(10,0);
SWV_Active_YN_Flag NVARCHAR2(1);
SWV_VarStr long;--varchar2(4000);
SWV_TRANCOUNT NUMBER(10,0);
SWV_fnc_SplitString_Id_var1 NUMBER(10,0);
SWV_fnc_SplitString_Id_var0 NUMBER(10,0);
CURSOR RestrictTermsheetVisibilityByC
IS select CS.Setting_Name,Default_Value,Config_Value
from Config_Settings CS LEFT OUTER JOIN Entity_Config EC ON EC.Setting_ID = CS.Setting_ID
where EC.Entity_ID = v_Entity_ID AND Setting_Level = 'ENTITY';
CURSOR Get_RestrictCCY_List_Cursor IS SELECT Id_1,Data_1 FROM table(fnc_SplitString(v_Config_Value,','));
--CURSOR Get_RestrictCCY_List_Cursor IS SELECT Id,Data FROM imp;
CURSOR GetRestrictTemplateListCursor
-- is select id,data from imp;
IS SELECT Id_1,Data_1 FROM table(fnc_SplitString(v_Config_Value,',')) ;
--Parikshit 18-Jul-2010, active YN flag param added in SP
BEGIN
SWV_Active_YN_Flag := v_Active_YN_Flag;
if SWV_Active_YN_Flag = ' ' then
SWV_Active_YN_Flag := 'Y';
end if;
v_SelectSQL := ' ';
v_SelectSQL := v_SelectSQL || ' Select ';
v_SelectSQL := v_SelectSQL || ' NM.Note_Master_Id, NM.Product_Name, NM.Template_ID, NM.Template_Sr_No, NM.Asset, NM.Exchange, NM.Type, NM.Currency';
--SET @SelectSQL = @SelectSQL + ' , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.Type like '' ELN%'' or NM.Type like ''RELN%'') THEN NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.Type like '' ELN%'' or NM.Type like ''RELN%'') THEN NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield, NOP.Dealer_Cost_PA as Internal_Cost '
v_SelectSQL := v_SelectSQL || ' , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.PriceList_YN = ''Y'') THEN NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.PriceList_YN = ''Y'') THEN NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield, NOP.Dealer_Cost_PA as Internal_Cost ';
v_SelectSQL := v_SelectSQL || ' , NM.Minimum_Issue_Size, NM.Maximum_Issue_Size, NM.Minimum_Tolerence_Amount, NM.Maximum_Tolerence_Amount, NM.Trigger_Amount_Warning, nvl(NM.PerUnit_Equivalent_Amount,1) as PerUnit_Equivalent_Amount, NM.Active_YN_Flag, NM.Verify_YN_Flag ';
v_SelectSQL := v_SelectSQL || ' , NM.Tranche_YN_Flag, NM.Launch_Date, NM.Open_Date, NM.Close_Date, NM.PreHedged_YN, NM.Created_By, NM.Created_At, NM.Verified_At, NM.Verified_By, NM.ISIN, NM.Issuer';
v_SelectSQL := v_SelectSQL || ' , NM.Product_Catagory as Product_Category, NM.Note_Issuer_Type as Issuer_Category, NM.Series_No as Series_No, NM.Minimum_Investment_Amount ';
--Added by Parikshit on 14-Jun-2011, to remove the unwinding amounts from the total issue size
--SET @SelectSQL = @SelectSQL + ' , NOP.LastTimeWhenProductModified,NOP.Nominal_Amount as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty '
v_SelectSQL := v_SelectSQL || ' , NOP.LastTimeWhenProductModified,(NOP.Nominal_Amount - nvl(ND.Unwind_Amount,0) ) as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty ';
--********************************************************END
v_SelectSQL := v_SelectSQL || ' ,T2.Confirmed_Amount, T2.Confirmed_Shares';
v_SelectSQL := v_SelectSQL || ' , T3.Live_Deals';
v_SelectSQL := v_SelectSQL || ' , BS.Net_Trade_Hedged, BS.Net_Trade_Outstanding, BS.Hedged_Nominal_BUY, BS.Hedged_Nominal_SELL, BS.Outstanding_Nominal_BUY, BS.Outstanding_Nominal_SELL ';
v_SelectSQL := v_SelectSQL || ' , ( case When UPPER(NM.PreHedged_YN) = ''Y'' Then ''Launched'' ';
v_SelectSQL := v_SelectSQL || ' When ((NM.Maturity_Date IS NOT NULL) AND to_date(NM.Maturity_Date) <= to_date(sysdate)) Then ''Matured''';
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NOT NULL) Then ''Launched''';
--Ready to launch
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= NM.Minimum_Issue_Size) AND to_date(Close_Date) > to_date(sysdate) ) Then ''Ready To Launch''';
--Ready to launch
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)= to_date(sysdate) ) Then ''Ready To Launch''';
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)< to_date(sysdate) ) Then ''Ready To Launch''';
--Warning trigger reached
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NOT NULL AND (T2.Confirmed_Amount >= NM.Trigger_Amount_Warning )) Then ''Warning Trigger Reached''';
v_SelectSQL := v_SelectSQL || ' Else ''Not Ready'' ';
v_SelectSQL := v_SelectSQL || ' End)Launch_Status';
v_SelectSQL := v_SelectSQL || ' , NI.Issuer_Code';
v_SelectSQL := v_SelectSQL || ' , (nvl(NOP.Nominal_Amount,0) - nvl(T2.Confirmed_Amount,0)) as Unconfirmed_Amount, NM.Upfront as Upfront, case when UPPER(NM.PreHedged_YN) = ''Y'' THEN 0 else (nvl(T2.Confirmed_Amount,0) - nvl(BS.Net_Trade_Hedged,0)) end as ReadyToHedge';
v_SelectSQL := v_SelectSQL || ' , NOP.Hard_Margin as Margin_Amount, NM.YearBasis as YearBasis, NM.Note_Product_Rating as Equity_Risk_Score, AD.Equity_Asset_Class ';
v_SelectSQL := v_SelectSQL || ' , NM.Note_Product_Rating as Product_Rating, NOP.PO_ID, AD.LotSize as Lot_Size, NM.Max_Orders_Per_Product as MAX_Orders, NOP.Order_Count as Current_Order_Count, nvl(NM.Denomination_Ccy,NM.Currency) as Denomination_Ccy, NM.Note_Scheme_Type as Underlying_Type, NM.Note_Asset_Class as Asset_Class, NULL as Product_Created_YN, NULL as Product_Created_ID, ( (case when NM.Note_Order_Type = '''' then N''Market'' else NM.Note_Order_Type end ) ) as Order_Type, NOP.Spot_Price, NM.Note_Price_Link, NOP.Strike_Price, NVL(NM.C_Fixing_Frequency,''Atmaturity'') as Fixing_Frequency, NM.Document_Uploaded_YN, NM.Document_Uploaded_At, NM.Document_Uploaded_By, NM.Document_File_Name, NM.Document_File_Extension, NM.Document_File_Path, NM.CutOff_Time, NM.Soft_Tenor, NM.NM_Sn_Code_All, NULL as Note_Price_Source, AD.LongName, NVL(NM.Pricelist_YN,''N'') as Pricelist_YN, AD.AlternateIdentifierAlias as Underlying, NM.Note_Issuer_Date_Offset, NM.Counterparty as Note_Counter_Party, NULL as
Note_Premium_PC ';
v_SelectSQL := v_SelectSQL || ' , NI.Issuer_Name, IP.Issuer_Id, IP.Broad_Cash, IP.Odd_Cash, IP.Account_Note, IP.Rounding, IP.Decimal_Truncate, IP.Misc1 as Recidual_YN, NM.Note_Issuer_Type, NM.Target_Coupon, C_Fixing_Frequency as C_Fixing_Frequency, NM.Callable_Frequency as Callable_Frequency, NM.Strike_Price_Percentage as C_Note_Strike_PC, NM.NM_Airbag_PC as Airbag_PC, C_Note_Barrier_PC as C_Note_Barrier_PC, TM.Template_Name, ''Product'' as Record_Type, NM.C_Settlement_Frequency, NM.Coupon_Frequency, NM.NM_Fixing_Source as Note_Fixing_Source, NM.Order_Entry_Type, (nvl(NM.Minimum_Issue_Size,0) - nvl(T2.Confirmed_Amount,0)) as Remaining_Launch_Amount, NM.C_Fixing_Start_Point, NM.C_Fixing_End_Point, NM.Order_Entry_Type, SC.Scheme_Alias, SC.Scheme_Name, CM.CM_ID, CM.CM_Name as Counterparty_Name, NM.NM_Other_Features as Other_Features, NM.Strike_Price_Percentage as Accrual_Strike, NM.NM_KnockIn as KnockIn, NM.NM_Airbag_Type, NM.NM_Put_strike as Put_Strike, NM.NM_Accrual_Strike,
NM.NM_Counterparty_Upfront, NM.Price_Updated_YN as Prices_Updated_YN, AD.Code as Asset_Name,NULL as KO_FREQ_TYPE, NM.Daily_Accumalation_Equities, NM.MaxNoAcc_days, NM.Guaranteed_Days, NM.Leverage_ratio, NM.NORM_IF, NM.NORM_PAIR, NM.NORM_FXRate ';
v_SelectSQL := v_SelectSQL || ' from ';
v_SelectSQL := v_SelectSQL || v_CommonDBName|| '.Note_Master NM ';
v_SelectSQL := v_SelectSQL || 'Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Issuer_Master NI ';
v_SelectSQL := v_SelectSQL || ' On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (NI.Issuer_Name as nvarchar2(25)) else cast(NI.Issuer_Id as nvarchar2(25)) end )';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Note_Order_Product NOP ';
v_SelectSQL := v_SelectSQL || ' On NOP.Note_Master_ID = NM.Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_DefinitionDBName||'.AssetDef AD ';
v_SelectSQL := v_SelectSQL || ' On AD.Code = NM.Asset';
v_SelectSQL := v_SelectSQL || ' AND AD.TypeAsset = substr(NM.Note_Asset_Class,1,2) ';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Issuer_Parameter IP ';
v_SelectSQL := v_SelectSQL || ' On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (IP.Issuer_Name as nvarchar2(25)) else cast(IP.Issuer_Id as nvarchar2(25)) end )';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Template_Master TM ';
v_SelectSQL := v_SelectSQL || ' On TM.Template_Id = NM.Template_ID ';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Scheme_Codes SC ';
v_SelectSQL := v_SelectSQL || ' On SC.Scheme_Alias = NM.Type';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Counterparty_Master CM ';
v_SelectSQL := v_SelectSQL || ' On CM.CM_ID = NM.Counterparty';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || ' ( ';
v_SelectSQL := v_SelectSQL || ' Select Note_master_ID, sum(Nominal_Amt) as Unwind_Amount from ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Note_Deals ';
v_SelectSQL := v_SelectSQL || ' where Prematurity_Date IS NOT NULL';
v_SelectSQL := v_SelectSQL || ' AND (UPPER(Deletion_Reason ) = ''PART REDEMPTION'' or UPPER(Deletion_Reason ) = ''FULL REDEMPTION'')';
v_SelectSQL := v_SelectSQL || ' Group by Note_master_ID ';
v_SelectSQL := v_SelectSQL || ' ) ND ';
v_SelectSQL := v_SelectSQL || ' On ND.Note_Master_ID = NM.Note_Master_ID';
if (v_Filter_FilledStatus = ' ' OR UPPER(v_Filter_FilledStatus) = 'ALL' ) then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NOP.Filled_Status IN (' || v_Filter_FilledStatus || ')';
end if;
--AND NOP.Internal_Counterparty = 'DEFAULT''
if(SUBSTR(to_char(v_Filter_Internal_Counterparty),1,4000)= ' ') then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NOP.Internal_Counterparty IN (' || v_Filter_Internal_Counterparty || ')';
end if;
--SET @SelectSQL = @SelectSQL + ' --Filter--'
v_SelectSQL := v_SelectSQL || ' LEFT OUTER JOIN ';
v_SelectSQL := v_SelectSQL || ' (';
v_SelectSQL := v_SelectSQL || ' select Note_Master_ID, sum(Nominal_Amount) As Confirmed_Amount, sum(No_Of_Shares) As Confirmed_Shares ';
v_SelectSQL := v_SelectSQL || ' from '||v_CommonDBName||'.Note_Order_RM ';
v_SelectSQL := v_SelectSQL || ' Where substr(UPPER(Order_Status_Flag),1,6) = ''YYYYYY'' AND substr(substr(UPPER(Order_Status_Flag),1,7),-1,1) = ''N'' ';
v_SelectSQL := v_SelectSQL || ' group by Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' ) T2';
v_SelectSQL := v_SelectSQL || ' ON T2.Note_Master_ID = NM.Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' LEFT OUTER JOIN';
v_SelectSQL := v_SelectSQL || ' (';
v_SelectSQL := v_SelectSQL || ' Select ND.Note_Master_ID, sum(ND.Nominal_Amt) As Live_Deals ';
v_SelectSQL := v_SelectSQL || ' from '||v_CommonDBName||'.Note_Deals ND ';
v_SelectSQL := v_SelectSQL || ' where ND.Active_YNFlag = ''Y'' ';
v_SelectSQL := v_SelectSQL || ' group by Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' ) T3';
v_SelectSQL := v_SelectSQL || ' ON T3.Note_Master_ID = NM.Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' LEFT OUTER JOIN';
v_SelectSQL := v_SelectSQL || ' (';
v_SelectSQL := v_SelectSQL || ' SELECT NH_Note_Master_ID,';
v_SelectSQL := v_SelectSQL || ' (CAST(SUM(Hedged_Nominal_Buy) AS BINARY_FLOAT) -CAST(SUM(Hedged_Nominal_Sell) AS BINARY_FLOAT)) Net_Trade_Hedged,';
v_SelectSQL := v_SelectSQL || ' (CAST(SUM(Outstanding_Nominal_BUY) AS BINARY_FLOAT) -CAST(SUM(Outstanding_Nominal_SELL) AS BINARY_FLOAT)) Net_Trade_Outstanding,';
v_SelectSQL := v_SelectSQL || ' SUM(Hedged_Nominal_BUY) AS Hedged_Nominal_BUY,';
v_SelectSQL := v_SelectSQL || ' SUM(Hedged_Nominal_SELL) AS Hedged_Nominal_SELL,';
v_SelectSQL := v_SelectSQL || ' SUM(Outstanding_Nominal_BUY) AS Outstanding_Nominal_BUY,';
v_SelectSQL := v_SelectSQL || ' SUM(Outstanding_Nominal_SELL) As Outstanding_Nominal_SELL';
v_SelectSQL := v_SelectSQL || ' From';
v_SelectSQL := v_SelectSQL || ' (';
v_SelectSQL := v_SelectSQL || ' SELECT NH_Note_Master_ID,';
v_SelectSQL := v_SelectSQL || ' SUM(NH_Hedged_Nominal) AS Hedged_Nominal_BUY, 0 AS Hedged_Nominal_SELL,';
v_SelectSQL := v_SelectSQL || ' SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_BUY, 0 AS Outstanding_Nominal_SELL';
v_SelectSQL := v_SelectSQL || ' FROM '||v_CommonDBName||'.Note_Hedge ';
v_SelectSQL := v_SelectSQL || ' WHERE NH_Direction = ''BUY'' ';
v_SelectSQL := v_SelectSQL || ' GROUP BY NH_Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' Union';
v_SelectSQL := v_SelectSQL || ' SELECT NH_Note_Master_ID,';
v_SelectSQL := v_SelectSQL || ' 0 AS Hedged_Nominal_BUY, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_SELL,';
v_SelectSQL := v_SelectSQL || ' 0 AS Outstanding_Nominal_BUY, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_SELL';
v_SelectSQL := v_SelectSQL || ' FROM '||v_CommonDBName||'.Note_Hedge ';
v_SelectSQL := v_SelectSQL || ' WHERE NH_Direction = ''SELL'' ';
v_SelectSQL := v_SelectSQL || ' GROUP BY NH_Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' ) ';
v_SelectSQL := v_SelectSQL || ' GROUP BY NH_Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' ) BS';
v_SelectSQL := v_SelectSQL || ' ON BS.NH_Note_Master_ID = NM.Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' Where NM.Verify_YN_Flag = ''Y'' ';
v_SelectSQL := v_SelectSQL || ' AND NM.Active_YN_Flag = ''' || SWV_Active_YN_Flag || '''';
if(SUBSTR(to_char(v_Filter_NoteType),1,4000) = ' ' OR UPPER(v_Filter_NoteType) = 'ALL' ) then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NM.Type IN (' || v_Filter_NoteType || ')';
end if;
IF UPPER(v_Entity_ID) <> 'ALL' then
OPEN RestrictTermsheetVisibilityByC;
FETCH RestrictTermsheetVisibilityByC INTO v_Setting_Name,v_Default_Value,v_Config_Value;
WHILE RestrictTermsheetVisibilityByC%FOUND LOOP
--2) Convert comma separated ccy (CNY,HKD,USD) string to single quote ccy with comma separated Ccy ('CNY','HKD','USD') string
if (UPPER(v_Setting_Name) = 'RESTRICT_TERMSHEET_VISIBILITY_BY_CCY') then
if v_Config_Value is not null then
SELECT COUNT(Id_1) INTO SWV_fnc_SplitString_Id_var0 FROM TABLE(fnc_SplitString(v_Config_Value,',')) ;
IF (SWV_fnc_SplitString_Id_var0 > 0) then
--print 'Before Single quote separated ccy : ' + '''' + @Config_Value + ''''
v_Seq_Id := 0;
OPEN Get_RestrictCCY_List_Cursor;
FETCH Get_RestrictCCY_List_Cursor
INTO v_CCY_ID,v_CCY_Data;
WHILE Get_RestrictCCY_List_Cursor%FOUND LOOP
if v_Seq_Id = 0 then
v_CCY_List := '''' || v_CCY_Data || '''';
else
v_CCY_List := v_CCY_List || ',' || '''' || v_CCY_Data || '''';
end if;
v_Seq_Id := v_Seq_Id+1;
FETCH Get_RestrictCCY_List_Cursor INTO v_CCY_ID,v_CCY_Data;
END LOOP;
CLOSE Get_RestrictCCY_List_Cursor;
--print 'After Single quote ccy : ' + @CCY_List
v_SelectSQL := v_SelectSQL || ' AND nvl(NM.Denomination_Ccy,NM.Currency) NOT IN (' || v_CCY_List || ')';
end if;
end if;
end if;
--3) Convert comma separated template (ELN,BELN,BELN_B) string to single quote template code with comma separated template ('ELN','BELN','BELN_B') string
if (UPPER(v_Setting_Name) = 'RESTRICT_TERMSHEET_VISIBILITY_BY_SUBSCHEME') then
if v_Config_Value is not null then
SELECT COUNT(Id_1) INTO SWV_fnc_SplitString_Id_var1 FROM TABLE(fnc_SplitString(v_Config_Value,',')) ;
IF (SWV_fnc_SplitString_Id_var1 > 0) then
v_Seq_Id := 0;
OPEN GetRestrictTemplateListCursor;
FETCH GetRestrictTemplateListCursor
INTO v_CCY_ID,v_CCY_Data;
WHILE GetRestrictTemplateListCursor%FOUND
LOOP
if v_Seq_Id = 0 then
v_CCY_List := '''' || v_CCY_Data || '''';
else
v_CCY_List := v_CCY_List || ',' || '''' || v_CCY_Data || '''';
end if;
v_Seq_Id := v_Seq_Id+1;
FETCH GetRestrictTemplateListCursor INTO v_CCY_ID,v_CCY_Data;
END LOOP;
CLOSE GetRestrictTemplateListCursor;
--print 'After Single quote template code: ' + @CCY_List
v_SelectSQL := v_SelectSQL || ' AND TM.Template_Code NOT IN (' || v_CCY_List || ')';
end if;
end if;
end if;
FETCH RestrictTermsheetVisibilityByC INTO v_Setting_Name,v_Default_Value,v_Config_Value;
END LOOP;
CLOSE RestrictTermsheetVisibilityByC;
end if;
if (v_Filter_Exchange = ' ' OR UPPER(v_Filter_Exchange) = 'ALL') then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NM.Exchange IN (' || v_Filter_Exchange || ')';
end if;
--SET @SelectSQL = @SelectSQL + ' --AND NM.Issuer = 4'
if (v_Filter_Issuer = ' ' OR UPPER(v_Filter_Issuer) = 'ALL') then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NM.Issuer IN (' || v_Filter_Issuer || ')';
end if;
if v_Filter_Product_Category = ' ' then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND UPPER(NM.Note_Issuer_Type) IN (''' || v_Filter_Product_Category || ''')';
end if;
if UPPER(v_DateToFilter) = 'NA' then
v_SelectSQL := v_SelectSQL || ' ';
else
if UPPER(v_DateToFilter) = 'CLOSE_DATE' then
v_SelectSQL := v_SelectSQL || ' AND to_char( '|| v_DateToFilter || ') >= to_date(''' || v_Filter_ToDate || ''');
-- AND convert(smalldatetime,''' || v_Filter_ToDate || ''',106) ';
else
v_SelectSQL := v_SelectSQL || ' AND to_char(''' || v_DateToFilter || ''') BETWEEN to_date(''' || v_Filter_FromDate || ''') AND to_date(''' || v_Filter_ToDate || ''') ';
end if;
end if;
v_SelectSQL := v_SelectSQL || ' Order by NM.Product_Name';
SWV_VarStr := v_SelectSQL;
DBMS_OUTPUT.PUT_LINE(SWV_VarStr);
EXECUTE IMMEDIATE SWV_VarStr;
IF SQLCODE <> 0 then
GOTO ERROR_HANDLER;
end if;
IF SQL%rowcount > 0 then
COMMIT;
SWV_TRANCOUNT := SWV_TRANCOUNT -1;
end if; --Commit Transaction
v_ErrorNumber := SQLCODE;
RETURN;
<< ERROR_HANDLER >> v_ErrorNumber := SQLCODE;
ROLLBACK;
SWV_TRANCOUNT := 0; --Rollback Transaction
RETURN;
END;Please suggest something. Thanks
Edited by: BluShadow on 30-Nov-2011 11:00
added {noformat}{noformat} tags for formatting of code. Please read {message:id=9360002} to learn to do this yourself in future.Connecting to the database sample_adf_finiq_common.
Select NM.Note_Master_Id, NM.Product_Name, NM.Template_ID, NM.Template_Sr_No, NM.Asset, NM.Exchange, NM.Type, NM.Currency , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.PriceList_YN = 'Y') THEN NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.PriceList_YN = 'Y') THEN NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield, NOP.Dealer_Cost_PA as Internal_Cost , NM.Minimum_Issue_Size, NM.Maximum_Issue_Size, NM.Minimum_Tolerence_Amount, NM.Maximum_Tolerence_Amount, NM.Trigger_Amount_Warning, nvl(NM.PerUnit_Equivalent_Amount,1) as PerUnit_Equivalent_Amount, NM.Active_YN_Flag, NM.Verify_YN_Flag , NM.Tranche_YN_Flag, NM.Launch_Date, NM.Open_Date, NM.Close_Date, NM.PreHedged_YN, NM.Created_By, NM.Created_At, NM.Verified_At, NM.Verified_By, NM.ISIN, NM.Issuer , NM.Product_Catagory as Product_Category, NM.Note_Issuer_Type as Issuer_Category, NM.Series_No as Series_No, NM.Minimum_Investment_Amount , NOP.LastTimeWhenProductModified,(NOP.Nominal_Amount - nvl(ND.Unwind_Amount,0) ) as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty ,T2.Confirmed_Amount, T2.Confirmed_Shares , T3.Live_Deals , BS.Net_Trade_Hedged, BS.Net_Trade_Outstanding, BS.Hedged_Nominal_BUY, BS.Hedged_Nominal_SELL, BS.Outstanding_Nominal_BUY, BS.Outstanding_Nominal_SELL , ( case When UPPER(NM.PreHedged_YN) = 'Y' Then 'Launched' When ((NM.Maturity_Date IS NOT NULL) AND to_date(NM.Maturity_Date) <= to_date(sysdate)) Then 'Matured' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NOT NULL) Then 'Launched' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= NM.Minimum_Issue_Size) AND to_date(Close_Date) > to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)= to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)< to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NOT NULL AND (T2.Confirmed_Amount >= NM.Trigger_Amount_Warning )) Then 'Warning Trigger Reached' Else 'Not Ready' End)Launch_Status , NI.Issuer_Code , (nvl(NOP.Nominal_Amount,0) - nvl(T2.Confirmed_Amount,0)) as Unconfirmed_Amount, NM.Upfront as Upfront, case when UPPER(NM.PreHedged_YN) = 'Y' THEN 0 else (nvl(T2.Confirmed_Amount,0) - nvl(BS.Net_Trade_Hedged,0)) end as ReadyToHedge , NOP.Hard_Margin as Margin_Amount, NM.YearBasis as YearBasis, NM.Note_Product_Rating as Equity_Risk_Score, AD.Equity_Asset_Class , NM.Note_Product_Rating as Product_Rating, NOP.PO_ID, AD.LotSize as Lot_Size, NM.Max_Orders_Per_Product as MAX_Orders, NOP.Order_Count as Current_Order_Count, nvl(NM.Denomination_Ccy,NM.Currency) as Denomination_Ccy, NM.Note_Scheme_Type as Underlying_Type, NM.Note_Asset_Class as Asset_Class, NULL as Product_Created_YN, NULL as Product_Created_ID, ( (case when NM.Note_Order_Type = '' then N'Market' else NM.Note_Order_Type end ) ) as Order_Type, NOP.Spot_Price, NM.Note_Price_Link, NOP.Strike_Price, NVL(NM.C_Fixing_Frequency,'Atmaturity') as Fixing_Frequency, NM.Document_Uploaded_YN, NM.Document_Uploaded_At, NM.Document_Uploaded_By, NM.Document_File_Name, NM.Document_File_Extension, NM.Document_File_Path, NM.CutOff_Time, NM.Soft_Tenor, NM.NM_Sn_Code_All, NULL as Note_Price_Source, AD.LongName, NVL(NM.Pricelist_YN,'N') as Pricelist_YN, AD.AlternateIdentifierAlias as Underlying, NM.Note_Issuer_Date_Offset, NM.Counterparty as Note_Counter_Party, NULL as
Note_Premium_PC , NI.Issuer_Name, IP.Issuer_Id, IP.Broad_Cash, IP.Odd_Cash, IP.Account_Note, IP.Rounding, IP.Decimal_Truncate, IP.Misc1 as Recidual_YN, NM.Note_Issuer_Type, NM.Target_Coupon, C_Fixing_Frequency as C_Fixing_Frequency, NM.Callable_Frequency as Callable_Frequency, NM.Strike_Price_Percentage as C_Note_Strike_PC, NM.NM_Airbag_PC as Airbag_PC, C_Note_Barrier_PC as C_Note_Barrier_PC, TM.Template_Name, 'Product' as Record_Type, NM.C_Settlement_Frequency, NM.Coupon_Frequency, NM.NM_Fixing_Source as Note_Fixing_Source, NM.Order_Entry_Type, (nvl(NM.Minimum_Issue_Size,0) - nvl(T2.Confirmed_Amount,0)) as Remaining_Launch_Amount, NM.C_Fixing_Start_Point, NM.C_Fixing_End_Point, NM.Order_Entry_Type, SC.Scheme_Alias, SC.Scheme_Name, CM.CM_ID, CM.CM_Name as Counterparty_Name, NM.NM_Other_Features as Other_Features, NM.Strike_Price_Percentage as Accrual_Strike, NM.NM_KnockIn as KnockIn, NM.NM_Airbag_Type, NM.NM_Put_strike as Put_Strike, NM.NM_Accrual_Strike,
NM.NM_Counterparty_Upfront, NM.Price_Updated_YN as Prices_Updated_YN, AD.Code as Asset_Name,NULL as KO_FREQ_TYPE, NM.Daily_Accumalation_Equities, NM.MaxNoAcc_days, NM.Guaranteed_Days, NM.Leverage_ratio, NM.NORM_IF, NM.NORM_PAIR, NM.NORM_FXRate from Sample_ADF_finiq_Common.Note_Master NM Left Outer Join Sample_ADF_finiq_Common.Issuer_Master NI On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (NI.Issuer_Name as nvarchar2(25)) else cast(NI.Issuer_Id as nvarchar2(25)) end ) Left Outer Join Sample_ADF_finiq_Common.Note_Order_Product NOP On NOP.Note_Master_ID = NM.Note_Master_ID Left Outer Join Sample_ADF_finiq_Common.AssetDef AD On AD.Code = NM.Asset AND AD.TypeAsset = substr(NM.Note_Asset_Class,1,2) Left Outer Join Sample_ADF_finiq_Common.Issuer_Parameter IP On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (IP.Issuer_Name as nvarchar2(25)) else cast(IP.Issuer_Id as nvarchar2(25)) end ) Left Outer Join Sample_ADF_finiq_Common.Template_Master TM On TM.Template_Id = NM.Template_ID Left Outer Join Sample_ADF_finiq_Common.Scheme_Codes SC On SC.Scheme_Alias = NM.Type Left Outer Join Sample_ADF_finiq_Common.Counterparty_Master CM On CM.CM_ID = NM.Counterparty Left Outer Join ( Select Note_master_ID, sum(Nominal_Amt) as Unwind_Amount from Sample_ADF_finiq_Common.Note_Deals where Prematurity_Date IS NOT NULL AND (UPPER(Deletion_Reason ) = 'PART REDEMPTION' or UPPER(Deletion_Reason ) = 'FULL REDEMPTION') Group by Note_master_ID ) ND On ND.Note_Master_ID = NM.Note_Master_ID AND NOP.Internal_Counterparty IN (1) LEFT OUTER JOIN ( select Note_Master_ID, sum(Nominal_Amount) As Confirmed_Amount, sum(No_Of_Shares) As Confirmed_Shares from Sample_ADF_finiq_Common.Note_Order_RM Where substr(UPPER(Order_Status_Flag),1,6) = 'YYYYYY' AND substr(substr(UPPER(Order_Status_Flag),1,7),-1,1) = 'N' group by Note_Master_ID ) T2 ON T2.Note_Master_ID = NM.Note_Master_ID LEFT OUTER JOIN ( Select ND.Note_Master_ID, sum(ND.Nominal_Amt) As Live_Deals from Sample_ADF_finiq_Common.Note_Deals ND where ND.Active_YNFlag = 'Y' group by Note_Master_ID ) T3 ON T3.Note_Master_ID = NM.Note_Master_ID LEFT OUTER JOIN ( SELECT NH_Note_Master_ID, (CAST(SUM(Hedged_Nominal_Buy) AS BINARY_FLOAT) -CAST(SUM(Hedged_Nominal_Sell) AS BINARY_FLOAT)) Net_Trade_Hedged, (CAST(SUM(Outstanding_Nominal_BUY) AS BINARY_FLOAT) -CAST(SUM(Outstanding_Nominal_SELL) AS BINARY_FLOAT)) Net_Trade_Outstanding, SUM(Hedged_Nominal_BUY) AS Hedged_Nominal_BUY, SUM(Hedged_Nominal_SELL) AS Hedged_Nominal_SELL, SUM(Outstanding_Nominal_BUY) AS Outstanding_Nominal_BUY, SUM(Outstanding_Nominal_SELL) As Outstanding_Nominal_SELL From ( SELECT NH_Note_Master_ID, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_BUY, 0 AS Hedged_Nominal_SELL, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_BUY, 0 AS Outstanding_Nominal_SELL FROM Sample_ADF_finiq_Common.Note_Hedge WHERE NH_Direction = 'BUY' GROUP BY NH_Note_Master_ID Union SELECT NH_Note_Master_ID, 0 AS Hedged_Nominal_BUY, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_SELL, 0 AS Outstanding_Nominal_BUY, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_SELL FROM Sample_ADF_finiq_Common.Note_Hedge WHERE NH_Direction = 'SELL' GROUP BY NH_Note_Master_ID ) GROUP BY NH_Note_Master_ID ) BS ON BS.NH_Note_Master_ID = NM.Note_Master_ID Where NM.Verify_YN_Flag = 'Y' AND NM.Active_YN_Flag = 'Y' AND UPPER(NM.Note_Issuer_Type) IN ('Internal') AND to_char('16-oct-11') BETWEEN to_date('15-oct-11') AND to_date('17-oct-11') Order by NM.Product_Name
V_ERRORNUMBER = 0
Process exited.
Disconnecting from the database sample_adf_finiq_common.
here v_errornumber=0 is the output when i run it in oracle sql developer. -
Need Help in Splitting a String Using SQL QUERY
Hi,
I need help in splitting a string using a SQL Query:
String IS:
AFTER PAINT.ACOUSTICAL.1..9'' MEMBRAIN'I would like to seperate this string into multiple lines using the delimeter .(dot)
Sample Output should look like:
SNO STRING
1 AFTER PAINT
2 ACOUSTICAL
3 1
4
5 9" MEMBRAIN
{code}
FYI i am using Oracle 9.2There's this as well:
with x as ( --generating sample data:
select 'AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN' str from dual union all
select 'BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN' str from dual)
select str,
row_number() over (partition by str order by rownum) s_no,
cast(dbms_xmlgen.convert(t.column_value.extract('//text()').getstringval(),1) as varchar2(100)) res
from x,
table(xmlsequence(xmltype('<x><x>' || replace(str,'.','</x><x>') || '</x></x>').extract('//x/*'))) t;
STR S_NO RES
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 1 AFTER PAINT
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 2 ACOUSTICAL
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 3 1
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 4
AFTER PAINT.ACOUSTICAL.1..9" MEMBRAIN 5 9" MEMBRAIN
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 1 BEFORE PAINT
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 2 ELECTRIC
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 3 2
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 4
BEFORE PAINT.ELECTRIC.2..45 caliber MEMBRAIN 5 45 caliber MEMBRAIN
{code} -
XML Generation using a sql query in an efficient way -Help needed urgently
Hi
I am facing the following issue while generating xml using an sql query. I get the below given table using a query.
CODE ID MARK
==================================
1 4 2331 809
2 4 1772 802
3 4 2331 845
4 5 2331 804
5 5 2331 800
6 5 2210 801
I need to generate the below given xml using a query
<data>
<CODE>4</CODE>
<IDS>
<ID>2331</ID>
<ID>1772</ID>
</IDS>
<MARKS>
<MARK>809</MARK>
<MARK>802</MARK>
<MARK>845</MARK>
</MARKS>
</data>
<data>
<CODE>5</CODE>
<IDS>
<ID>2331</ID>
<ID>2210</ID>
</IDS>
<MARKS>
<MARK>804</MARK>
<MARK>800</MARK>
<MARK>801</MARK>
</MARKS>
</data>
Can anyone help me with some idea to generate the above given CLOB messagenot sure if this is the right way to do it but
/* Formatted on 10/12/2011 12:52:28 PM (QP5 v5.149.1003.31008) */
WITH data AS (SELECT 4 code, 2331 id, 809 mark FROM DUAL
UNION
SELECT 4, 1772, 802 FROM DUAL
UNION
SELECT 4, 2331, 845 FROM DUAL
UNION
SELECT 5, 2331, 804 FROM DUAL
UNION
SELECT 5, 2331, 800 FROM DUAL
UNION
SELECT 5, 2210, 801 FROM DUAL)
SELECT TO_CLOB (
'<DATA>'
|| listagg (xml, '</DATA><DATA>') WITHIN GROUP (ORDER BY xml)
|| '</DATA>')
xml
FROM ( SELECT '<CODE>'
|| code
|| '</CODE><IDS><ID>'
|| LISTAGG (id, '</ID><ID>') WITHIN GROUP (ORDER BY id)
|| '</ID><IDS><MARKS><MARK>'
|| LISTAGG (mark, '</MARK><MARK>') WITHIN GROUP (ORDER BY id)
|| '</MARK></MARKS>'
xml
FROM data
GROUP BY code) -
I'm attempting to dynamically generate a rather large SQL query via the "PL/SQL function body returning SQL query" report region option. The SQL query generated will possibly be over 32K. When I execute my page, I sometimes receive the "ORA-06502: PL/SQL: numeric or value error" which points to a larger than 32K query that was generated. I've seen other posts in the forum related to this dynamic SQL size limitation issue, but they are older (pre-2010) and point to the 32K limit of the DNS (EXECUTE IMMEDIATE) and DBMS_SQL. I found this post (dynamic sql enhancements in 11g) which discusses 11g no longer having the 32K size limitation for generating dynamic SQL. Our environment is on 11gR2 and using ApEx 4.2.1. I do not know which dynamic SQL method -- DNS or DBMS_SQL -- ApEx 4.2.1 is using. Can someone clarify for me which dynamic SQL method ApEx uses to implement the "PL/SQL function body returning SQL query" option?
As a test, I created a page on apex.oracle.com with a report region with the following source:
declare
l_stub varchar2(25) := 'select * from sys.dual ';
l_sql clob := l_stub || 'union all ';
br number(3) := 33;
begin
while length ( l_sql ) < 34000 loop
l_sql := l_sql || l_stub || 'union all ';
end loop;
l_sql := l_sql || l_stub;
for i in 1 .. ceil ( length ( l_sql ) / br ) loop
dbms_output.put_line ( dbms_lob.substr ( l_sql, br, ( ( i - 1 ) * br ) + 1 ) );
end loop;
return l_sql;
end;
The dbms_output section is there to be able to run this code in SQL*Plus and confirm the size of the SQL is indeed larger than 32K. When running this in SQL*Plus, the procedure is successful and produces a proper SQL statement which can be executed. When I put this into the report region on apex.oracle.com, I get the ORA-06502 error.
I can certainly implement a work-around for my issue by creating a 'Before Header' process on the page which populates an ApEx collection with the data I am returning and then the report can simply select from the collection, but according to documentation, the above 32K limitation should be resolved in 11g. Thoughts?
Shane.What setting do you use in your report properties - especially in Type and in Region Source?
If you have Type="SQL Query", then you should have a SELECT statement in the Region Source. Something like: SELECT .... FROM ... WHERE
According to the ERR-1101 error message, you have probably set Type to "SQL Query (PL/SQL function body returning SQL query)". In this situation APEX expects you to write a body of a PL/SQL function, that will generate the text of a SQL query that APEX should run. So it can be something like:
declare
mycond varchar2(4000);
begin
if :P1_REPORT_SEARCH is not null THEN
mycond:='WHERE LAST_NAME like :P1_REPORT_SEARCH ||''%''';
end if;
return 'select EMPLOYEE_ID, FIRST_NAME, LAST_NAME from EMPLOYEES ' ||mycond;
end;
And for escaping - are you interested in escaping the LIKE wildcards, or the quotes?
For escaping the wildcards in LIKE function so that when the user enters % you will find a record with % and not all functions, look into the SQL Reference:
http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/conditions007.htm
(You would than need to change the code of your function accordingly).
If you are interested in escaping the quotes, try to avoid concatenating the values entered by the user into the SQL. If you can, use bind variables instead - as I have in my example above. If you start concatenating the values into the text of SQL, you are open to SQLInjection - user can enter anything, even things that will break your SQL. If you really need to allow users to choose the operator, I would probably give them a separate combo for operators and a textfield for values, than you could check if the operator is one of the allowed ones and create the condition accordingly - and than still use bind variable for inserting the filtering value into the query. -
SQL Query for full paid invoices and payed out credit notes
Hi alltogether,
I have some problems with a sql query.
I want to export all closed (full paid) invoices and credit notes in a table with the paid date.
The problem is that I have several internal reconciliations for one invoice or credit note.
So with my current query I get all these dates in the result but only for invoices, not for credit notes.
I only need the last internal reconciliation date as payment date for all invoices and credit notes where the open amount is 0.
In SAP B1 the finance team has service invoices and credit notes imported out of an ERP system.
These documents are marked with an 'Y" in the coloumn "U_I_Imported" in the table "OINV" or "ORIN".
SELECT
OINV.DocTotal - OINV.PaidToDate as Offen, OINV.NumAtCard, OINV.U_I_Imported, ORCT.DocDate as 'Zahlungsdatum'
SELECT
OINV.DocTotal - OINV.PaidToDate as Offen, OINV.NumAtCard, OINV.U_I_Imported, ORCT.DocDate as 'Zahlungsdatum'
FROM
OJDT inner join
ORCT on OJDT.BaseRef = ORCT.DocNum inner join
RCT2 on ORCT.DocNum = RCT2.DocNum inner join
OINV on RCT2.BaseAbs = OINV.DocEntry
where
OINV.DocTotal - OINV.PaidToDate = 0 and OINV.U_I_Imported = 'Y'
group by
OINV.NumatCard, OINV.DocTotal - OINV.PaidToDate, OINV.U_I_Imported, ORCT.DocDate
order by
ORCT.DocDate
I hope you can help me.
Kind regards,
MaxThe solution for my problem:
select
OINV.DocTotal - OINV.PaidToDate as 'Offen', OINV.CardCode as 'Kundennummer', OINV.NumAtCard as 'DIAMOD Rechnungsnummer', OINV.DocNum as 'Dokumentennummer', max(ORCT.DocDate) as 'Zahlungsdatum', case when ORCT.DocCurr = (select MainCurncy from OADM) then RCT2.DcntSum else RCT2.DcntSumFC end as 'SkontoRechnungswährung',
RCT2.DcntSum as 'SkontoFirmenwährung'
from
JDT1 inner join
OJDT on JDT1.TransId = OJDT.TransId inner join
ORCT on OJDT.BaseRef = ORCT.DocNum inner join
RCT2 on ORCT.DocNum = RCT2.DocNum inner join
OINV on RCT2.BaseAbs = OINV.DocEntry
where
JDT1.TransType in ('24') and
OINV.U_I_Imported = 'Y' and
OINV.DocTotal - OINV.PaidToDate = 0
group by
OINV.NumAtCard, OINV.DocNum, OINV.CardCode, OINV.DocTotal - OINV.PaidToDate, ORCT.DocCurr, RCT2.DcntSum, RCT2.DcntSumFC
union all
select
OINV.DocTotal - OINV.PaidToDate as Offen, OINV.CardCode as 'Kundennummer', OINV.NumAtCard as 'DIAMOD Rechnungsnummer', OINV.DocNum as 'Dokumentennummer', max(OITR.ReconDate) as 'Zahlungsdatum',
0.0 as 'SkontoRechnungswährung',
0.0 as 'SkontoFirmenwährung'
from
OITR inner join
ITR1 on OITR.ReconNum = ITR1.ReconNum inner join
OINV on ITR1.SrcObjAbs = OINV.DocEntry
where
OINV.DocTotal - OINV.PaidToDate = 0 and ITR1.SrcObjTyp = 13 and OINV.U_I_Imported = 'Y'
group by
OINV.NumatCard, OINV.DocNum, OINV.CardCode, OINV.DocTotal - OINV.PaidToDate
union all
select
ORIN.DocTotal - ORIN.PaidToDate as Offen, ORIN.CardCode as 'Kundennummer', ORIN.NumAtCard as 'DIAMOD Rechnungsnummer', ORIN.DocNum as 'Dokumentennummer', max(OITR.ReconDate) as 'Zahlungsdatum',
0.0 as 'SkontoRechnungswährung',
0.0 as 'SkontoFirmenwährung'
from
OITR inner join
ITR1 on OITR.ReconNum = ITR1.ReconNum inner join
ORIN on ITR1.SrcObjAbs = ORIN.DocEntry
where
ORIN.DocTotal - ORIN.PaidToDate = 0 and ITR1.SrcObjTyp = 14 and ORIN.U_I_Imported = 'Y'
group by
ORIN.NumatCard, ORIN.DocNum, ORIN.CardCode, ORIN.DocTotal - ORIN.PaidToDate -
How Can I Change the Where Condition In the First SQL Query?
SELECT IND_SSN, BEG_SVC_DT, END_SVC_DT,
TRUNC(MONTHS_BETWEEN((TO_DATE('19'||END_SVC_DT,'YYYYMMDD')),BEG_SVC_DT)/12),
mod(trunc(months_between((to_date('19'||end_svc_dt,'YYYYMMDD')),BEG_SVC_DT)),12),
DECODE((SUBSTR(END_SVC_DT,5,2) - SUBSTR(BEG_SVC_DT,1,2)+1),-1,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-2,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-3,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-4,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-5,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-6,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-7,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-8,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-9,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-10,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-11,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-12,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-13,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-14,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-15,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-16,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-17,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-18,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-19,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-20,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-21,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-22,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-23,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-24,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-25,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-26,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-27,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-28,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-29,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-30,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
-31,((SUBSTR(END_SVC_DT,5,2)+ 31) - SUBSTR(BEG_SVC_DT,1,2)),
30,0,
(SUBSTR(END_SVC_DT,5,2) - SUBSTR(BEG_SVC_DT,1,2)+1))
FROM SVC_OCCURRENCES
WHERE end_svc_dt not in ('PRESENT')
AND SUBSTR(END_SVC_DT,1,1) IN '9'
AND SUBSTR(END_SVC_DT,5,2) NOT IN ('31')
and (SUBSTR(END_SVC_DT,5,2) - SUBSTR(BEG_SVC_DT,1,2)+1) not in ('30')
UNION
SELECT IND_SSN, BEG_SVC_DT, END_SVC_DT, NULL, NULL, NULL
FROM SVC_OCCURRENCES
WHERE SUBSTR(END_SVC_DT,1,1) IN 'P'
The above code works fine and I get the correct numeric values from the SQL
query when the varchar2 end_svc_dt field is numeric however if I have encoded
the word 'PRESENT' in the varchar2 end_svc dt field the SQL query aborts at
the last statement in the WHERE condition. The beg_svc_dt field is a Date field.
and (SUBSTR(END_SVC_DT,5,2) - SUBSTR(BEG_SVC_DT,1,2)+1) not in ('30')
I get the following error message
ERROR ORA-0722 INVALID NUMBER
I encode the word 'PRESENT' in a varchar2 end_svc_dt field on an Oracle form. This is the only word that can be encoded.
Is there some way that I can bypass the last statement in the where condition and
compute the values from the SQL query without having the SQL query abort?
Eventually I want to do this in a report. I know that this sounds strange but can it be done?The above code works fine and I get the correct
numeric values from the SQL
query when the varchar2 end_svc_dt field is numeric
however if I have encoded
the word 'PRESENT' in the varchar2 end_svc dt field
the SQL query aborts at
the last statement in the WHERE condition.Ouch!
Storting dates in VARCHAR2 columns is bad practice, poor design and makes for horrible code.
The beg_svc_dt field is a Date field.
and (SUBSTR(END_SVC_DT,5,2) -
SUBSTR(BEG_SVC_DT,1,2)+1) not in ('30')If it's a date field then why on earth are you trying to SUBSTR it. SUBSTR = sub-string i.e. take a sub section of a string not sub-date.
I get the following error message
ERROR ORA-0722 INVALID NUMBERAnd you're surprised by this?
Is there some way that I can bypass the last
statement in the where condition and
compute the values from the SQL query without having
the SQL query abort?Store your dates properly, use additional flag columns for non-date information and code your SQL properly.
Eventually I want to do this in a report. I know
that this sounds strange but can it be done?Yes, most things are possible. -
Not to able add sql query in the item source
Hi,
I am getting this error when i am trying to add the sql query in the item source
ORA-20505: Error in DML: p_rowid=3206911131098131, p_alt_rowid=ID, p_rowid2=, p_alt_rowid2=. ORA-01461: can bind a LONG value only for insert into a LONG column
SELECT
"UCL"
FROM
SELECT
TRUNC((
(SUM("EV FINAL" / 100) / COUNT("Object_Name") )
+
3 *
SQRT
(SUM("EV FINAL" / 100) * SUM("EV FINAL" / 100) ) / COUNT("Object_Name") -
(SUM("EV FINAL" / 100) / COUNT("Object_Name")) * (SUM("EV FINAL" / 100) / COUNT("Object_Name"))
),3) "UCL"
FROM
SELECT
Pro.Project_Name "Project Name",
POBJ.NAME "Object_Name",
TRUNC((
( ( NVL(AEV."Total Actual",0) - (NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(ID."INCOMMING_DOC",0) ) ,0 ) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(D."DESIGN",0) ), 0 ) +
NVL( (NVL( (MAX(X."Build") / 100) ,0) * NVL(B."BUILD",0) ),0 ) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(T."TESTING",0) ),0 ) +
NVL( (NVL( (MAX(X."Release") / 100),0) * NVL(R."RELEASE",0) ),0 ) ) )
DECODE(
(NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(ID."INCOMMING_DOC",0) ) ,0 ) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(D."DESIGN",0) ), 0 ) +
NVL( (NVL( (MAX(X."Build") / 100) ,0) * NVL(B."BUILD",0) ),0 ) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(T."TESTING",0) ),0 ) +
NVL( (NVL( (MAX(X."Release") / 100),0) * NVL(R."RELEASE",0) ),0 ) ),0,NULL,
(NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(ID."INCOMMING_DOC",0) ) ,0 ) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(D."DESIGN",0) ), 0 ) +
NVL( (NVL( (MAX(X."Build") / 100) ,0) * NVL(B."BUILD",0) ),0 ) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(T."TESTING",0) ),0 ) +
NVL( (NVL( (MAX(X."Release") / 100),0) * NVL(R."RELEASE",0) ),0 ) ) ) ) * 100),2)
|| '%' "EV_INITIAL",
TRUNC((
( (NVL(AEV."Total Actual",0) - ( NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(IDR."INCOMMING_DOC_REPLAN",0) ),0) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(DR."DESIGN_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Build")/100),0) * NVL(BR."BUILD_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(TR."TESTING_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Release")/100),0) * NVL(RR."RELEASE_REPLAN",0)),0) ) )
DECODE(
( NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(IDR."INCOMMING_DOC_REPLAN",0) ),0) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(DR."DESIGN_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Build")/100),0) * NVL(BR."BUILD_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(TR."TESTING_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Release")/100),0) * NVL(RR."RELEASE_REPLAN",0)),0) ) ,0,NULL,
( NVL( (NVL( (MAX(X."Incoming-Doc") / 100),0) * NVL(IDR."INCOMMING_DOC_REPLAN",0) ),0) +
NVL( (NVL( (MAX(X."Design") / 100),0) * NVL(DR."DESIGN_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Build")/100),0) * NVL(BR."BUILD_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Testing") / 100),0) * NVL(TR."TESTING_REPLAN",0)),0) +
NVL( (NVL( (MAX(X."Release")/100),0) * NVL(RR."RELEASE_REPLAN",0)),0) ) ) ) * 100),2) "EV FINAL",
TRUNC(BRV."RSV",2) "Revised SV"
FROM
PROJECTS PRO,
PROJECT_OBJECTS POBJ,
INITIAL_EFFORT IE,
SCHEDULE_VARIANCES SV,
INITIAL_EFFORT_VIEW IEV,
INCOMMING_DOC ID,
DESIGN D,
BUILD B,
TESTING T,
RELEASE R,
INCOMMING_DOC_REPLAN IDR,
DESIGN_REPLAN DR,
BUILD_REPLAN BR,
TESTING_REPLAN TR,
RELEASE_REPLAN RR,
ACTUAL_EFFORT_VIEW AEV,
REPLAN_INITIAL_EFFORT_VIEW RIEV,
BSV_RSV_VIEW BRV,
SELECT
distinct
pro.project_name "Project Name",
pobj.name "Object Name",
PRO.ID "PRO_ID",
POBJ.ID "POBJ_ID",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review') THEN
TO_CHAR('100')
WHEN
upper(ts.status) like upper('ACCEPTED') AND
tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review') THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review')
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Incoming-Doc",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Design Review','Design - Review','TDD - Review') THEN
TO_CHAR('100')
WHEN
UPPER(ts.status) LIKE UPPER('ACCEPTED') AND
tsk.name in ('Design Review','Design - Review','TDD - Review') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Design Review','Design - Review','TDD - Review')
THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Design Review','Design - Review','TDD - Review')
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Design",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Build Review','Build - Review','Code - Review','Code') THEN
TO_CHAR('100')
WHEN
UPPER(ts.status) LIKE UPPER('ACCEPTED') AND
tsk.name in ('Build Review','Build - Review','Code - Review','Code') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Build Review','Build - Review','Code - Review','Code') THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Build Review','Build - Review','Code - Review','Code')
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Build",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Test Result Review','Test Result - Review','UTR - Review') THEN
TO_CHAR('100')
WHEN
UPPER(ts.status) LIKE UPPER('ACCEPTED') AND
tsk.name in ('Test Result Review','Test Result - Review','UTR - Review') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Test Result Review','Test Result - Review','UTR - Review') THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Test Result Review','Test Result - Review','UTR - Review')
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Testing",
CASE
WHEN
ts.status in ('CLOSE','CLOSED','Closed') AND
tsk.name in ('Release-Review','Release - Verification',
'Migration & Release - Review') THEN
TO_CHAR('100')
WHEN
UPPER(ts.status) LIKE UPPER('ACCEPTED') AND
tsk.name in ('Release-Review','Release - Verification',
'Migration & Release - Review') THEN
TO_CHAR('75')
WHEN
ts.status IN ('RIP','WIP','REJECTED','Rejected') AND
tsk.name in ('Release-Review','Release - Verification','Migration & Release - Review') THEN
TO_CHAR('50')
WHEN
POBJ.ID IN (SELECT POBJ.ID FROM projects pro,project_objects pobj,task tsk,skip_phase sp,employees
emp,employee_project_pairs epp
WHERE pobj.pro_id = pro.id and epp.pro_id = pro.id AND sp.tas_id = tsk.id and
pobj.id = sp.OBJ_ID and pro.id = sp.pro_id
and tsk.name in ('Release-Review','Release - Verification','Migration & Release - Review' )
AND PRO.ID = :p2_projects ) THEN
TO_CHAR('100')
END "Release"
FROM
task_status ts,projects pro,project_objects pobj,task tsk
,employees emp,employee_project_pairs epp,REVIEW_ITEMS RI
WHERE
pobj.pro_id = pro.id
and pro.id = ts.pro_id
and pobj.id = ts.pro_obj_id
and tsk.id = ts.task_id
and emp.id = epp.emp_id
and epp.pro_id = pro.id
and ts.id = ri.ts_id
AND PRO.ID = :p2_projects
and tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review','Design Review','Design - Review','TDD - Review',
'Build Review','Build - Review','Code - Review','Code',
'Test Result Review','Test Result - Review','UTR - Review',
'Release-Review','Release - Verification','Migration & Release - Review')
and ri.open_timestamp in
SELECT
distinct
max(ri.open_timestamp)
FROM
task_status ts,projects pro,project_objects pobj,task tsk
,employees emp,employee_project_pairs epp,REVIEW_ITEMS RI
WHERE
pobj.pro_id = pro.id
and pro.id = ts.pro_id
and pobj.id = ts.pro_obj_id
and tsk.id = ts.task_id
and emp.id = epp.emp_id
and epp.pro_id = pro.id
and ts.id = ri.ts_id
and tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review','Design Review','Design - Review','TDD - Review',
'Build Review','Build - Review','Code - Review','Code',
'Test Result Review','Test Result - Review','UTR - Review',
'Release-Review','Release - Verification','Migration & Release - Review')
AND PRO.ID = :p2_projects
GROUP BY POBJ.NAME,TSK.NAME )
UNION
select
distinct
pro.project_name "Project Name",
pobj.name "Object Name",
PRO.ID "PRO_ID",
POBJ.ID "POBJ_ID",
case
when
tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review') THEN
TO_CHAR('100')
end "Incoming-Doc",
case
when
tsk.name in ('Design Review','Design - Review','TDD - Review') THEN
TO_CHAR('100')
end "Design",
case
when
tsk.name in ('Build Review','Build - Review','Code - Review','Code') THEN
TO_CHAR('100')
end "Build",
case
when
tsk.name in ('Test Result Review','Test Result - Review','UTR - Review') THEN
TO_CHAR('100')
end "Testing",
case
when
tsk.name in ('Release-Review','Release - Verification',
'Migration & Release - Review') THEN
TO_CHAR('100')
end "Release"
FROM
projects pro
,project_objects pobj
,task tsk
,skip_phase sp
,employees emp
,employee_project_pairs epp
WHERE
pobj.pro_id = pro.id
and epp.pro_id = pro.id
AND sp.tas_id = tsk.id
and pobj.id = sp.OBJ_ID
and pro.id = sp.pro_id
and tsk.name in ('Incomming-Doc Review','Incoming Doc- Review',
'Incoming Doc- Review','FDD - Review','Design Review','Design - Review',
'TDD - Review','Build Review','Build - Review','Code - Review','Code',
'Test Result Review','Test Result - Review','UTR - Review',
'Release-Review','Release - Verification','Migration & Release - Review')
and pro.id = :p2_projects ) X
WHERE
PRO.ID = POBJ.PRO_ID AND
PRO.ID = IE.PROJECT_NAME AND
UPPER(POBJ.NAME) = UPPER(IE.OBJECT_NAME) AND
PRO.ID = SV.PROJECT_NAME AND
UPPER(POBJ.NAME) = UPPER(SV.OBJECT_NAME) AND
PRO.ID = :p2_projects
AND PRO.ID = X."PRO_ID"
AND POBJ.ID = X."POBJ_ID"(+)
AND PRO.ID = IEV."PRO_ID"
AND POBJ.ID = IEV."POBJ_ID"
AND PRO.ID = ID."PRO_ID"
AND POBJ.ID = ID."POBJ_ID"
AND PRO.ID = D."PRO_ID"
AND POBJ.ID = D."POBJ_ID"
AND PRO.ID = B."PRO_ID"
AND POBJ.ID = B."POBJ_ID"
AND PRO.ID = T."PRO_ID"
AND POBJ.ID = T."POBJ_ID"
AND PRO.ID = R."PRO_ID"
AND POBJ.ID = R."POBJ_ID"
AND PRO.ID = IDR."PRO_ID"
AND POBJ.ID = IDR."POBJ_ID"
AND PRO.ID = DR."PRO_ID"
AND POBJ.ID = DR."POBJ_ID"
AND PRO.ID = BR."PRO_ID"
AND POBJ.ID = BR."POBJ_ID"
AND PRO.ID = TR."PRO_ID"
AND POBJ.ID = TR."POBJ_ID"
AND PRO.ID = RR."PRO_ID"
AND POBJ.ID = RR."POBJ_ID"
AND PRO.ID = AEV."PRO_ID"
AND POBJ.ID = AEV."POBJ_ID"
AND PRO.ID = RIEV."PRO_ID"
AND POBJ.ID = RIEV."POBJ_ID"
AND PRO.ID = BRV."PRO_ID"
AND POBJ.ID = BRV."POBJ_ID"
group by
PRO.PROJECT_NAME,
POBJ.NAME,
SV.status,
sv.comments,
ID."INCOMMING_DOC",D."DESIGN",B."BUILD",T."TESTING",R."RELEASE",
IDR."INCOMMING_DOC_REPLAN",DR."DESIGN_REPLAN",BR."BUILD_REPLAN",TR."TESTING_REPLAN",RR."RELEASE_REPLAN",
AEV."Total Actual",IEV."Total Plan",RIEV."Total Plan",
BRV."BSV",BRV."RSV",POBJ.Complexity,POBJ.PROGRAM_TYPE,pro.id,pobj.id,BRV."Status"
wht is the mistake i am doing here please suggets
thanks
SudhirCan you just setup an Excel/Essbase retrieval to get the data you need? You can't use SQL to query Essbase; here is a blog post that talks about it:
http://timtows-hyperion-blog.blogspot.com/2008/01/why-you-cant-use-sql-to-query-essbase.html
Since I made that post, I have found out that Essbase has now been integrated into the latest version of the Oracle BI Server and, technically, you could use SQL to query the data in Essbase via the Oracle BI Server if you have the right version.
Tim Tow
Applied OLAP, Inc -
Hi,
in "Show" section of my prompt i've following SQL Query:
select Country."Company Description" from Prototype where Country."Country Code Company GOAL Code" IN
(Select Entity_Relationship.Company from Prototype where Entity_Relationship.Parent
IN (Select Entity. "HFM Entities" from Prototype where Entity.Description ='@{Entity}'))
UNION
select Country."Company Description" from Prototype where Country."Country Code Company GOAL Code" IN
(Select Entity_Relationship.Company from Prototype where Entity_Relationship.Child
IN (Select Entity. "HFM Entities" from Prototype where Entity.Description ='@{Entity}'))
It returns Company Descriptions where id equal presentation variable. And it works fine. Now i want that if query returns an empty resultset, it must returns a default string 'Not Defined Country'. How can i modify my query?
Thanks
GiancarloHi,
it doesn't work because presentation variable will be always filled. The whole query can return an empty resultset, but presentation variable will have always a value. I try to explain better...
My query (composed by two queries linked by Union clause) can return one or more Country."Company Description" records, but it can return even 0 rows. Now when it returns 0 rows my prompt will be an empty prompt (no choices). Now i want that if it so, query must return a default string "Not defined Country". In my opinion i must add to my query other clauses like EXISTS, NOT EXISTS, IN, NOT IN, or case when clause. But how?
Thanks
Giancarlo -
Hi All,
I have belwo two record values.
select 1 as seq_no,'test1' as data_set from dual
union
select 1,'12test' from dual
union
select 2,'abcd' from dual
union
select 2,'ilm' from dual
union
select 2,'12test444' from dual
here i need to extract the below o/p from from the above dataset
1,12test
1,test1
2,12test444
select 1 as seq_no,'test1' as data_set from dual
union
select 1,'12test' from dual
union
select 2,'abcd' from dual
union
select 2,'ilm' from dual
here i need to extract the below o/p from from the above dataset
1,12test
1,test1
2,abcd
2,ilm
The logic behind the above two types of o/p is
if the search string 'test' is present in any data set (data set is defined by same seq_no values) then print the whole row containing the search string. As in the first record value data set with seq_val 1 and 2 both have test string 'test' , o/p is all the rows contating the search string 'test'
If the search string 'test' is not present in any data set (data set is defined by same seq_no values) then print all other rows not containing the search string. As in the second record value data set with seq_val 2 both doesn't have test string 'test' , o/p is all the rows not contating the search string 'test' in data test with seq_val 1as well as all the rows contating the search string 'test' in data set with seq_val 2
Hope i could explain my o/p logic and i need to perform this in a sql query.
Waiting for your responses.
Thanks in advance.Hi,
Here's one way:
WITH got_rnk AS
SELECT seq_no, data_set
, DENSE_RANK () OVER ( PARTITION BY seq_no
ORDER BY CASE
WHEN INSTR (data_set, 'test') > 0
THEN 1
ELSE 2
END
) AS rnk
FROM table_x
SELECT seq_no, data_set
FROM got_rnk
WHERE rnk = 1
;The CASE expression returns 1 if data_set contains 'test', and it returns 2 if it does not. Let's call this number x.
You're not really interested in x itself. Rather, you want all the rows that have the lowest value of x among rows with the same seq_no. That is, if any row with a given_seq_num has x=1, then you want all rows with that seq_no and x=1, but it the lowest x for the a seq_no is 2, then you want the rows with x=2 instead.
DENSE_RANK returns the the number 1 if the given riow is the lowest (or tied for the lowest) in its partition, so if the are any rows with x=1 in the group, rnk=1 will correspond to x=1. But if all the rows with the same seq_no have x=2, then rnk=1 will correspond to x=2. -
Set the column length in an sql query
Hi,
Is there a way to set the column length in a query without using sqlplus commands like row size and format column.
I'd like to do it just from the sql query itself.
select 'this is a test' from dual; Can I define the width of this column in the select statement
Cheers.Use RPAD,
SQL> WITH T
2 AS (SELECT 'this is test' str FROM DUAL
3 UNION ALL
4 SELECT 'this is a long test' FROM DUAL
5 UNION ALL
6 SELECT 'this is a long long long long test' FROM DUAL)
7 SELECT RPAD ( str, 20) str,LENGTH( RPAD ( str, 20)) len
8 FROM T;
STR LEN
this is test 20
this is a long test 20
this is a long long 20
SQL> G. -
SQL Query for mapping a set of batches to a class rooms group
Hi All,
I am using Oracle 11g Release 2 database.
I have the following data set:
ClassRooms
ClassId ClassName Capacity Group
1 Babbage/Software Engg Lab 24 1
2 Basement - PG Block 63 1
3 Classroom 1 56 1
4 Classroom 10 24 1
5 Classroom 11 24 1
6 Classroom 12 35 1
7 Classroom 13 42 1
8 Classroom 14 42 1
9 Classroom 15 42 1
10 Classroom 2 35 1
11 Classroom 3 35 1
12 Classroom 4 35 1
13 Classroom 5 35 1
14 Classroom 6 25 1
15 Classroom 7 25 1
16 Classroom 8 24 1
17 Classroom 9 24 1
18 Control Sys Lab 24 1
19 Dig & Embd Sys Lab 20 1
20 DSP & Comm Lab 20 1
21 Electromechanical System Lab 28 1
22 Farabi/Web Tech Lab 36 1
23 Gen Purpose Lab 40 1
24 Shirazi/DB Tech Lab 36 1
25 Adv Elect Lab 30 2
26 Classroom 16 42 2
27 Classroom 17 49 2
28 Classroom 18 56 2
29 Classroom 19 42 2
30 Classroom 20 49 2
31 Classroom 21 35 3
32 Classroom 22 35 3
33 MDA Lab 20 3
DegreeBatches
BatchId BatchName Strength
1 BIT-11 79
2 BIT-12 28
3 BS(CS)-1 35
4 BS(CS)-2 78
5 BE(SE)-1 69
6 BE(SE)-2 84
7 BE(SE)-3 64
8 BICSE-7 84
9 BICSE-8 43
10 BEE-1 112
11 BEE-2 151
12 BEE-3 157
13 BEE-4 157
I want to map a degree batch combination to a class rooms group in such away that they fully utilize maximum capacity of the class rooms within a group (Ideal case) or as close to it as possible. Can it be done with a SQL query?
Any response will be highly appreciated.
SQL Scripts to generate the required tables and populate data is below:
CREATE TABLE ClassRooms (ClassId NUMBER, ClassName VARCHAR2(50), Capacity NUMBER, Group NUMBER);
INSERT INTO ClassRooms VALUES(1,'Babbage/Software Engg Lab',24,1);
INSERT INTO ClassRooms VALUES(2,'Basement - PG Block',63,1);
INSERT INTO ClassRooms VALUES(3,'Classroom 1',56,1);
INSERT INTO ClassRooms VALUES(4,'Classroom 10',24,1);
INSERT INTO ClassRooms VALUES(5,'Classroom 11',24,1);
INSERT INTO ClassRooms VALUES(6,'Classroom 12',35,1);
INSERT INTO ClassRooms VALUES(7,'Classroom 13',42,1);
INSERT INTO ClassRooms VALUES(8,'Classroom 14',42,1);
INSERT INTO ClassRooms VALUES(9,'Classroom 15',42,1);
INSERT INTO ClassRooms VALUES(10,'Classroom 2',35,1);
INSERT INTO ClassRooms VALUES(11,'Classroom 3',35,1);
INSERT INTO ClassRooms VALUES(12,'Classroom 4',35,1);
INSERT INTO ClassRooms VALUES(13,'Classroom 5',35,1);
INSERT INTO ClassRooms VALUES(14,'Classroom 6',25,1);
INSERT INTO ClassRooms VALUES(15,'Classroom 7',25,1);
INSERT INTO ClassRooms VALUES(16,'Classroom 8',24,1);
INSERT INTO ClassRooms VALUES(17,'Classroom 9',24,1);
INSERT INTO ClassRooms VALUES(18,'Control Sys Lab',24,1);
INSERT INTO ClassRooms VALUES(19,'Dig & Embd Sys Lab',20,1);
INSERT INTO ClassRooms VALUES(20,'DSP & Comm Lab',20,1);
INSERT INTO ClassRooms VALUES(21,'Electromechanical System Lab',28,1);
INSERT INTO ClassRooms VALUES(22,'Farabi/Web Tech Lab',36,1);
INSERT INTO ClassRooms VALUES(23,'Gen Purpose Lab',40,1);
INSERT INTO ClassRooms VALUES(24,'Shirazi/DB Tech Lab',36,1);
INSERT INTO ClassRooms VALUES(25,'Adv Elect Lab',30,2);
INSERT INTO ClassRooms VALUES(26,'Classroom 16',42,2);
INSERT INTO ClassRooms VALUES(27,'Classroom 17',49,2);
INSERT INTO ClassRooms VALUES(28,'Classroom 18',56,2);
INSERT INTO ClassRooms VALUES(29,'Classroom 19',42,2);
INSERT INTO ClassRooms VALUES(30,'Classroom 20',49,2);
INSERT INTO ClassRooms VALUES(31,'Classroom 21',35,3);
INSERT INTO ClassRooms VALUES(32,'Classroom 22',35,3);
INSERT INTO ClassRooms VALUES(33,'MDA Lab',20,3);
CREATE TABLE DegreeBatches (BatchId NUMBER, BatchName VARCHAR2(50), Strength NUMBER);
INSERT INTO DegreeBatches VALUES(1,'BIT-11',79);
INSERT INTO DegreeBatches VALUES(2,'BIT-12',28);
INSERT INTO DegreeBatches VALUES(3,'BS(CS)-1',35);
INSERT INTO DegreeBatches VALUES(4,'BS(CS)-2',78);
INSERT INTO DegreeBatches VALUES(5,'BE(SE)-1',69);
INSERT INTO DegreeBatches VALUES(6,'BE(SE)-2',84);
INSERT INTO DegreeBatches VALUES(7,'BE(SE)-3',64);
INSERT INTO DegreeBatches VALUES(8,'BICSE-7',84);
INSERT INTO DegreeBatches VALUES(9,'BICSE-8',43);
INSERT INTO DegreeBatches VALUES(10,'BEE-1',112);
INSERT INTO DegreeBatches VALUES(11,'BEE-2',151);
INSERT INTO DegreeBatches VALUES(12,'BEE-3',157);
INSERT INTO DegreeBatches VALUES(13,'BEE-4',157);
Best Regards
Bilal
Edited by: Bilal on 27-Dec-2012 09:52
Edited by: Bilal on 27-Dec-2012 10:07Bilal, thanks for the nice problem! Another possibility for duplicate checking is to write a small PL/SQL function returning 1 if a duplicate id is found, then equate it to 0: 'Duplicate_Token_Found (p_str_main VARCHAR2, p_str_trial VARCHAR2) RETURN NUMBER'. This would parse the second string and might use p_str_main LIKE '%,' || l_id || ',%' for each id. Anyway the full query (without that) is given below:
Solution with names
SQL> WITH rsf_itm (con_id, max_weight, nxt_id, lev, tot_weight, tot_profit, path, root_id, lev_1_id) AS (
2 SELECT c.id,
3 c.max_weight,
4 i.id,
5 0,
6 i.item_weight,
7 i.item_profit,
8 ',' || i.id || ',',
9 i.id,
10 0
11 FROM items i
12 CROSS JOIN containers c
13 UNION ALL
14 SELECT r.con_id,
15 r.max_weight,
16 i.id,
17 r.lev + 1,
18 r.tot_weight + i.item_weight,
19 r.tot_profit + i.item_profit,
20 r.path || i.id || ',',
21 r.root_id,
22 CASE WHEN r.lev = 0 THEN i.id ELSE r.nxt_id END
23 FROM rsf_itm r
24 JOIN items i
25 ON i.id > r.nxt_id
26 AND r.tot_weight + i.item_weight <= r.max_weight
27 ORDER BY 1, 2
28 ) SEARCH DEPTH FIRST BY nxt_id SET line_no
29 , rsf_con (nxt_con_id, nxt_line_no, con_path, itm_path, tot_weight, tot_profit, lev) AS (
30 SELECT con_id,
31 line_no,
32 To_Char(con_id),
33 ':' || con_id || '-' || (lev + 1) || ':' || path,
34 tot_weight,
35 tot_profit,
36 0
37 FROM rsf_itm
38 UNION ALL
39 SELECT r_i.con_id,
40 r_i.line_no,
41 r_c.con_path || ',' || r_i.con_id,
42 r_c.itm_path || ':' || r_i.con_id || '-' || (r_i.lev + 1) || ':' || r_i.path,
43 r_c.tot_weight + r_i.tot_weight,
44 r_c.tot_profit + r_i.tot_profit,
45 r_c.lev + 1
46 FROM rsf_con r_c
47 JOIN rsf_itm r_i
48 ON r_i.con_id > r_c.nxt_con_id
49 WHERE r_c.itm_path NOT LIKE '%,' || r_i.root_id || ',%'
50 AND r_c.itm_path NOT LIKE '%,' || r_i.lev_1_id || ',%'
51 AND r_c.itm_path NOT LIKE '%,' || r_i.nxt_id || ',%'
52 )
53 , paths_ranked AS (
54 SELECT itm_path || ':' itm_path, tot_weight, tot_profit, lev + 1 n_cons,
55 Rank () OVER (ORDER BY tot_profit DESC) rnk,
56 Row_Number () OVER (ORDER BY tot_profit DESC) sol_id
57 FROM rsf_con
58 ), best_paths AS (
59 SELECT itm_path, tot_weight, tot_profit, n_cons, sol_id
60 FROM paths_ranked
61 WHERE rnk = 1
62 ), row_gen AS (
63 SELECT LEVEL lev
64 FROM DUAL
65 CONNECT BY LEVEL <= (SELECT Count(*) FROM items)
66 ), con_v AS (
67 SELECT b.itm_path, r.lev con_ind, b.sol_id, b.tot_weight, b.tot_profit,
68 Substr (b.itm_path, Instr (b.itm_path, ':', 1, 2*r.lev - 1) + 1,
69 Instr (b.itm_path, ':', 1, 2*r.lev) - Instr (b.itm_path, ':', 1, 2*r.lev - 1) - 1)
70 con_nit_id,
71 Substr (b.itm_path, Instr (b.itm_path, ':', 1, 2*r.lev) + 1,
72 Instr (b.itm_path, ':', 1, 2*r.lev + 1) - Instr (b.itm_path, ':', 1, 2*r.lev) - 1)
73 itm_str
74 FROM best_paths b
75 JOIN row_gen r
76 ON r.lev <= b.n_cons
77 ), con_split AS (
78 SELECT itm_path, con_ind, sol_id, tot_weight, tot_profit,
79 Substr (con_nit_id, 1, Instr (con_nit_id, '-', 1) - 1) con_id,
80 Substr (con_nit_id, Instr (con_nit_id, '-', 1) + 1) n_items,
81 itm_str
82 FROM con_v
83 ), itm_v AS (
84 SELECT c.itm_path, c.con_ind, c.sol_id, c.con_id, c.tot_weight, c.tot_profit,
85 Substr (c.itm_str, Instr (c.itm_str, ',', 1, r.lev) + 1,
86 Instr (c.itm_str, ',', 1, r.lev + 1) - Instr (c.itm_str, ',', 1, r.lev) - 1)
87 itm_id
88 FROM con_split c
89 JOIN row_gen r
90 ON r.lev <= c.n_items
91 )
92 SELECT v.sol_id,
93 v.tot_weight s_wt, v.tot_profit s_pr, c.id c_id, c.name c_name, c.max_weight m_wt,
94 Sum (i.item_weight) OVER (PARTITION BY v.sol_id, c.id) c_wt,
95 i.id i_id, i.name i_name, i.item_weight i_wt, i.item_profit i_pr
96 FROM itm_v v
97 JOIN containers c
98 ON c.id = To_Number (v.con_id)
99 JOIN items i
100 ON i.id = To_Number (v.itm_id)
101 ORDER BY sol_id, con_id, itm_id
102 /
SOL_ID S_WT S_PR C_ID C_NAME M_WT C_WT I_ID I_NAME I_WT I_PR
1 255 255 1 SEECS UG Block 100 100 1 BIT-10 35 35
2 BIT-11 40 40
6 BICSE-7 25 25
2 IAEC Building 70 70 4 BSCS-3 40 40
7 BESE-3 30 30
3 RIMMS Building 90 85 3 BSCS-2 35 35
5 BEE-4 50 50
2 255 255 1 SEECS UG Block 100 95 4 BSCS-3 40 40
6 BICSE-7 25 25
7 BESE-3 30 30
2 IAEC Building 70 70 1 BIT-10 35 35
3 BSCS-2 35 35
3 RIMMS Building 90 90 2 BIT-11 40 40
5 BEE-4 50 50
3 255 255 1 SEECS UG Block 100 100 3 BSCS-2 35 35
4 BSCS-3 40 40
6 BICSE-7 25 25
2 IAEC Building 70 65 1 BIT-10 35 35
7 BESE-3 30 30
3 RIMMS Building 90 90 2 BIT-11 40 40
5 BEE-4 50 50
4 255 255 1 SEECS UG Block 100 100 3 BSCS-2 35 35
4 BSCS-3 40 40
6 BICSE-7 25 25
2 IAEC Building 70 70 2 BIT-11 40 40
7 BESE-3 30 30
3 RIMMS Building 90 85 1 BIT-10 35 35
5 BEE-4 50 50
5 255 255 1 SEECS UG Block 100 95 2 BIT-11 40 40
6 BICSE-7 25 25
7 BESE-3 30 30
2 IAEC Building 70 70 1 BIT-10 35 35
3 BSCS-2 35 35
3 RIMMS Building 90 90 4 BSCS-3 40 40
5 BEE-4 50 50
6 255 255 1 SEECS UG Block 100 100 2 BIT-11 40 40
3 BSCS-2 35 35
6 BICSE-7 25 25
2 IAEC Building 70 65 1 BIT-10 35 35
7 BESE-3 30 30
3 RIMMS Building 90 90 4 BSCS-3 40 40
5 BEE-4 50 50
7 255 255 1 SEECS UG Block 100 100 2 BIT-11 40 40
3 BSCS-2 35 35
6 BICSE-7 25 25
2 IAEC Building 70 70 4 BSCS-3 40 40
7 BESE-3 30 30
3 RIMMS Building 90 85 1 BIT-10 35 35
5 BEE-4 50 50
8 255 255 1 SEECS UG Block 100 100 1 BIT-10 35 35
4 BSCS-3 40 40
6 BICSE-7 25 25
2 IAEC Building 70 70 2 BIT-11 40 40
7 BESE-3 30 30
3 RIMMS Building 90 85 3 BSCS-2 35 35
5 BEE-4 50 50
9 255 255 1 SEECS UG Block 100 100 1 BIT-10 35 35
4 BSCS-3 40 40
6 BICSE-7 25 25
2 IAEC Building 70 65 3 BSCS-2 35 35
7 BESE-3 30 30
3 RIMMS Building 90 90 2 BIT-11 40 40
5 BEE-4 50 50
10 255 255 1 SEECS UG Block 100 100 1 BIT-10 35 35
3 BSCS-2 35 35
7 BESE-3 30 30
2 IAEC Building 70 65 2 BIT-11 40 40
6 BICSE-7 25 25
3 RIMMS Building 90 90 4 BSCS-3 40 40
5 BEE-4 50 50
11 255 255 1 SEECS UG Block 100 100 1 BIT-10 35 35
3 BSCS-2 35 35
7 BESE-3 30 30
2 IAEC Building 70 65 4 BSCS-3 40 40
6 BICSE-7 25 25
3 RIMMS Building 90 90 2 BIT-11 40 40
5 BEE-4 50 50
12 255 255 1 SEECS UG Block 100 95 1 BIT-10 35 35
3 BSCS-2 35 35
6 BICSE-7 25 25
2 IAEC Building 70 70 2 BIT-11 40 40
7 BESE-3 30 30
3 RIMMS Building 90 90 4 BSCS-3 40 40
5 BEE-4 50 50
13 255 255 1 SEECS UG Block 100 95 1 BIT-10 35 35
3 BSCS-2 35 35
6 BICSE-7 25 25
2 IAEC Building 70 70 4 BSCS-3 40 40
7 BESE-3 30 30
3 RIMMS Building 90 90 2 BIT-11 40 40
5 BEE-4 50 50
14 255 255 1 SEECS UG Block 100 100 1 BIT-10 35 35
2 BIT-11 40 40
6 BICSE-7 25 25
2 IAEC Building 70 65 3 BSCS-2 35 35
7 BESE-3 30 30
3 RIMMS Building 90 90 4 BSCS-3 40 40
5 BEE-4 50 50
98 rows selected.
Elapsed: 00:00:01.42Edited by: BrendanP on 20-Jan-2013 11:25
I found the regex needed to deduplicate:
AND RegExp_Instr (r_c.itm_path || r_i.path, ',(\d+),.*?,\1,') = 0
Maybe you are looking for
-
How can I DELETE MY OLD CELL PHONE NUMBER
I can't get my old cell phone number out of my settings.I need a code to reset my password.I have put my new phone number in but keep getting my code sent to the old cell.Please help!!
-
Problem about Communication with Bluetooth
Hi all! I want to use a PC host to communicate with a mobile phone with Bluetooth technology. In details, the mobile phone wanting to know some informaiton about "news of today" firstly send a message to my PC, then my PC have to response with a repl
-
Why can I receive mail but not send?
I am receiving my gmail messages in apple mail but cannot send messages.
-
Can someone help with payment options?
It won't let me use a Amex or master card gift card to purchase songs. I have tried multiple cards. I don't have a credit card so I can't use that. When I got my phone I entered a gift card I'm not sure if it was Amex or master card and it worked but
-
I am in desperate need of help. Here is the path to my html file. http://www.3hounddesign.com/WoodsWoods/gallery/index.html When you look at it, you see the navigation list on the left (Adobe, SF Symphony, Fiery, etc). This list corresponds to the im