Recursive Sub-query Factoring... bug? or my own personal ignorance?
I was trying to create a list of all dates in the current month using a recursive sub-query factor. (Oracle 11.2)
I know how to do this by other methods; the question is, what's going on with this "WITH" example?
Here's my attempt at generating the list:
with
date_list ( crnt_mnth_date ) as
( select cast ( trunc(sysdate,'MM') as date ) from dual
UNION ALL
select crnt_mnth_date + interval '1' day
from date_list
where to_char(crnt_mnth_date,'MM') = to_char(sysdate,'MM')
select * from date_list ;The recursion should add one day to the previous date and continue while the generated dates are in the same month
as the current-date (sysdate). All I get is the first day of the month. In an attempt to figure this out I added the
sequence "n". To my surprise the recursion is subtracting instead of adding the one day each time.
with
date_list ( n, crnt_mnth_date ) as
( select 1, cast ( trunc(sysdate,'MM') as date ) from dual
UNION ALL
select n+1, crnt_mnth_date + (interval '1' day) as crnt_mnth_date
from date_list
where n < 9
select * from date_list ;And... Changing the "+" to a "-" still subtracts one day each time -- no change.
Obvious BUG? Or am I just confused on how this works?
Hi,
I've heard that the new recursive WITH clause feature is buggy, especially when DATEs are involved.
I get the same (unexpected) results that you do.
A very similar query, using only NUMBERs, does wotk as expected:
with
date_list ( n, crnt_mnth_num ) as
( select 1, 20010501 from dual
UNION ALL
select n+1, crnt_mnth_num + 1 as crnt_mnth_num
from date_list
where n < 9
select * from date_list ;Outptu:
` N CRNT_MNTH_NUM
1 20010501
2 20010502
3 20010503
4 20010504
5 20010505
6 20010506
7 20010507
8 20010508
9 20010509
Similar Messages
-
Recursive Sub-query Factoring vs Hierarchical Query
Experts,
The below are two queries i am executing by using classical approach hierarchical and newest recursive sub-query.Problem is output was different for recursive sub-query factoring, as this is not showing parent-child approach, while connect by prior is showing parent-child fashion.Query 1, i am using hierarchical as it showing correct output parent-child approach, while Query 2 is displaying all the level 1 nodes and then level 2 nodes.I want query 2 output to be same as query 1.Please modify query 2 as required.
Note:The output of the both queries won't be in displayed as it was in sqlplus, or toad.Please copy and use in your command prompts.
QUERY 1:
with main as(select 1 id,'john' name,null mgrid from dual union all
select 2 id,'michael' name,null mgrid from dual union all
select 3 id,'peter' name,null mgrid from dual union all
select 4 id,'henry' name,1 mgrid from dual union all
select 5 id,'nick' name,2 mgrid from dual union all
select 6 id,'pao' name,3 mgrid from dual union all
select 7 id,'kumar' name,3 mgrid from dual union all
select 8 id,'parker' name,3 mgrid from dual union all
select 9 id,'mike' name,5 mgrid from dual),
select lpad(' ',2*(level-1))||name name,level from main start with mgrid is null connect by prior id=mgrid;
OUTPUT :
NAME LEVEL
john 1
henry 2
michael 1
nick 2
mike 3
peter 1
pao 2
kumar 2
parker 2
9 rows selected.
QUERY 2:
with main as(select 1 id,'john' name,null mgrid from dual union all
select 2 id,'michael' name,null mgrid from dual union all
select 3 id,'peter' name,null mgrid from dual union all
select 4 id,'henry' name,1 mgrid from dual union all
select 5 id,'nick' name,2 mgrid from dual union all
select 6 id,'pao' name,3 mgrid from dual union all
select 7 id,'kumar' name,3 mgrid from dual union all
select 8 id,'parker' name,3 mgrid from dual union all
select 9 id,'mike' name,5 mgrid from dual),
/*select lpad(' ',2*(level-1))||name name,level from main start with mgrid is null connect by prior id=mgrid;*/
secmain (id,name,mgrid,hierlevel) as(select id,name,mgrid,1 hierlevel from main where mgrid is null
union all
select m.id,m.name,m.mgrid,sm.hierlevel+1 from main m join secmain sm on(m.mgrid=sm.id))
cycle id set is_cycle to 1 default 0
select lpad(' ',2*(hierlevel-1))||name name,hierlevel from secmain;
OUTPUT :
NAME HIERLEVEL
john 1
michael 1
peter 1
henry 2
nick 2
parker 2
kumar 2
pao 2
mike 3
9 rows selected.Hi,
What's wrong with Query 1? If it's producing the results you want, then why not use it?
One of the nice features of CONNECT BY is that the output is automatically presented in hierachical order. The only way I know of to get the results of a recursive WITH clause in any kind or order is to do it yourself. Here's one way:
WITH secmain (id, name, mgrid, hierlevel, path) AS
SELECT id
, name
, mgrid
, 1 AS hierlevel
, RPAD (name, 10) AS path -- Assuming name is never longer than 10
FROM main
WHERE mgrid IS NULL
UNION ALL
SELECT m.id
, m.name
, m.mgrid
, sm.hierlevel + 1
, sm.path || RPAD (name, 10)
FROM main m
JOIN secmain sm ON (m.mgrid = sm.id)
CYCLE id -- Why do you need this if CONNECT BY NOCYCLE wasn't needed in Query 1?
SET is_cycle TO 1
DEFAULT 0
SELECT lpad ( ' '
, 2 * (hierlevel - 1)
) || name AS name
, hierlevel
FROM secmain
ORDER BY path
;Sorry, I don't have an Oracle 11.2 database right now, so I can't test it.
Edited by: Frank Kulash on Nov 23, 2011 9:15 AM
I didn't know about the SEARCH clause, Use Dom's solution, above. -
Can i use Sub Query Factoring Here ?
Hi;
SQL>SELECT * FROM V$VERSION;
BANNER
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
PL/SQL Release 11.1.0.7.0 - Production
CORE 11.1.0.7.0 Production
TNS for Linux: Version 11.1.0.7.0 - Production
NLSRTL Version 11.1.0.7.0 - ProductionSQL
select /*+ PARALLEL(det, 4) */ '12062' snapshot_id,det.journal_entry_line_id, det.accounting_date,det.company_code,det.account_number,
det.transaction_id, det.transaction_id_type, det.amount,det.currency_code,det.debit_or_credit,det.category,det.subcategory,det.reference1,det.reference1_type,
det.reference2,det.reference2_type,det.gl_batch_id,det.marketplace_id,det.cost_center,det.gl_product_line,det.location,det.project,det.sales_channel,
det.created_by,det.creation_date,det.last_updated_by,det.last_updated_date,agg.age,last_day(to_date('04/21/2010','MM/DD/YYYY')) snapshot_day
from
select company_code, account_number, transaction_id,
decode(transaction_id_type, 'CollectionID', 'SettlementGroupID', transaction_id_type) transaction_id_type,
(last_day(to_date('04/21/2010','MM/DD/YYYY')) - min(z.accounting_date) ) age,sum(z.amount)
from
select /*+ PARALLEL(use, 2) */ company_code,substr(account_number, 1, 5) account_number,transaction_id,
decode(transaction_id_type, 'CollectionID', 'SettlementGroupID', transaction_id_type) transaction_id_type,use.amount,use.accounting_date
from financials.unbalanced_subledger_entries use
where use.accounting_date >= to_date('04/21/2010','MM/DD/YYYY')
and use.accounting_date < to_date('04/21/2010','MM/DD/YYYY') + 1
UNION ALL
select /*+ PARALLEL(se, 2) */ company_code, substr(se.account_number, 1, 5) account_number,transaction_id,
decode(transaction_id_type, 'CollectionID', 'SettlementGroupID', transaction_id_type) transaction_id_type,se.amount,se.accounting_date
from financials.temp2_sl_snapshot_entries se,financials.account_numbers an
where se.account_number = an.account_number
and an.subledger_type in ('C', 'AC')
) z
group by company_code,account_number,transaction_id,decode(transaction_id_type, 'CollectionID', 'SettlementGroupID', transaction_id_type)
having abs(sum(z.amount)) >= 0.01
) agg,
select /*+ PARALLEL(det, 2) */ det.journal_entry_line_id, det.accounting_date, det.company_code, det.account_number, det.transaction_id, decode(det.transaction_id_type, 'CollectionID', 'SettlementGroupID', det.transaction_id_type) transaction_id_type,
det.amount, det.currency_code, det.debit_or_credit, det.category, det.subcategory, det.reference1, det.reference1_type, det.reference2, det.reference2_type,
det.gl_batch_id, det.marketplace_id, det.cost_center, det.gl_product_line, det.location, det.project, det.sales_channel, det.created_by, det.creation_date,
det.last_updated_by, det.last_updated_date
from financials.unbalanced_subledger_entries det
where accounting_date >= to_date('04/21/2010','MM/DD/YYYY')
and accounting_date < to_date('04/21/2010','MM/DD/YYYY') + 1
UNION ALL
select /*+ PARALLEL(det, 2) */ det.journal_entry_line_id, det.accounting_date, det.company_code, det.account_number, det.transaction_id,
decode(det.transaction_id_type, 'CollectionID', 'SettlementGroupID', det.transaction_id_type) transaction_id_type, det.amount, det.currency_code,
det.debit_or_credit, det.category, det.subcategory, det.reference1, det.reference1_type, det.reference2, det.reference2_type, det.gl_batch_id, det.marketplace_id,
det.cost_center, det.gl_product_line, det.location, det.project, det.sales_channel, det.created_by, det.creation_date, det.last_updated_by, det.last_updated_date
from financials.temp2_sl_snapshot_entries det,financials.account_numbers an
where det.account_number = an.account_number
and an.subledger_type in ('C', 'AC')
) det
where agg.company_code = det.company_code
and agg.account_number = substr(det.account_number, 1, 5)
and agg.transaction_id = det.transaction_id
and agg.transaction_id_type = det.transaction_id_type
/Execution Plan
| Id | Operation | Name | Rows | Bytes |TempSpc| Cost (%CPU)| Time | TQ |IN-OUT| PQ Distrib |
| 0 | SELECT STATEMENT | | 12M| 8012M| | 541K (1)| 01:48:21 | | | |
| 1 | PX COORDINATOR | | | | | | | | | |
| 2 | PX SEND QC (RANDOM) | :TQ10005 | 12M| 8012M| | 541K (1)| 01:48:21 | Q1,05 | P->S | QC (RAND) |
|* 3 | HASH JOIN BUFFERED | | 12M| 8012M| 1098M| 541K (1)| 01:48:21 | Q1,05 | PCWP | |
| 4 | PX RECEIVE | | 35M| 3992M| | 166K (2)| 00:33:16 | Q1,05 | PCWP | |
| 5 | PX SEND HASH | :TQ10003 | 35M| 3992M| | 166K (2)| 00:33:16 | Q1,03 | P->P | HASH |
| 6 | VIEW | | 35M| 3992M| | 166K (2)| 00:33:16 | Q1,03 | PCWP | |
|* 7 | FILTER | | | | | | | Q1,03 | PCWC | |
| 8 | HASH GROUP BY | | 35M| 4528M| | 166K (2)| 00:33:16 | Q1,03 | PCWP | |
| 9 | PX RECEIVE | | 35M| 4528M| | 166K (2)| 00:33:16 | Q1,03 | PCWP | |
| 10 | PX SEND HASH | :TQ10001 | 35M| 4528M| | 166K (2)| 00:33:16 | Q1,01 | P->P | HASH |
| 11 | HASH GROUP BY | | 35M| 4528M| | 166K (2)| 00:33:16 | Q1,01 | PCWP | |
| 12 | VIEW | | 35M| 4528M| | 164K (1)| 00:33:00 | Q1,01 | PCWP | |
| 13 | UNION-ALL | | | | | | | Q1,01 | PCWP | |
| 14 | PX BLOCK ITERATOR | | 11 | 539 | | 1845 (1)| 00:00:23 | Q1,01 | PCWC | |
|* 15 | TABLE ACCESS FULL | UNBALANCED_SUBLEDGER_ENTRIES | 11 | 539 | | 1845 (1)| 00:00:23 | Q1,01 | PCWP | |
|* 16 | HASH JOIN | | 35M| 2012M| | 163K (1)| 00:32:37 | Q1,01 | PCWP | |
| 17 | BUFFER SORT | | | | | | | Q1,01 | PCWC | |
| 18 | PX RECEIVE | | 21 | 210 | | 2 (0)| 00:00:01 | Q1,01 | PCWP | |
| 19 | PX SEND BROADCAST | :TQ10000 | 21 | 210 | | 2 (0)| 00:00:01 | | S->P | BROADCAST |
|* 20 | TABLE ACCESS FULL| ACCOUNT_NUMBERS | 21 | 210 | | 2 (0)| 00:00:01 | | | |
| 21 | PX BLOCK ITERATOR | | 56M| 2701M| | 162K (1)| 00:32:35 | Q1,01 | PCWC | |
| 22 | TABLE ACCESS FULL | TEMP2_SL_SNAPSHOT_ENTRIES | 56M| 2701M| | 162K (1)| 00:32:35 | Q1,01 | PCWP | |
| 23 | PX RECEIVE | | 35M| 18G| | 82859 (1)| 00:16:35 | Q1,05 | PCWP | |
| 24 | PX SEND HASH | :TQ10004 | 35M| 18G| | 82859 (1)| 00:16:35 | Q1,04 | P->P | HASH |
| 25 | BUFFER SORT | | 12M| 8012M| | | | Q1,04 | PCWP | |
| 26 | VIEW | | 35M| 18G| | 82859 (1)| 00:16:35 | Q1,04 | PCWP | |
| 27 | UNION-ALL | | | | | | | Q1,04 | PCWP | |
| 28 | PX BLOCK ITERATOR | | 11 | 2255 | | 923 (1)| 00:00:12 | Q1,04 | PCWC | |
|* 29 | TABLE ACCESS FULL | UNBALANCED_SUBLEDGER_ENTRIES | 11 | 2255 | | 923 (1)| 00:00:12 | Q1,04 | PCWP | |
|* 30 | HASH JOIN | | 35M| 7514M| | 81936 (1)| 00:16:24 | Q1,04 | PCWP | |
| 31 | PX RECEIVE | | 21 | 210 | | 2 (0)| 00:00:01 | Q1,04 | PCWP | |
| 32 | PX SEND BROADCAST | :TQ10002 | 21 | 210 | | 2 (0)| 00:00:01 | Q1,02 | P->P | BROADCAST |
| 33 | PX BLOCK ITERATOR | | 21 | 210 | | 2 (0)| 00:00:01 | Q1,02 | PCWC | |
|* 34 | TABLE ACCESS FULL | ACCOUNT_NUMBERS | 21 | 210 | | 2 (0)| 00:00:01 | Q1,02 | PCWP | |
| 35 | PX BLOCK ITERATOR | | 56M| 11G| | 81840 (1)| 00:16:23 | Q1,04 | PCWC | |
| 36 | TABLE ACCESS FULL | TEMP2_SL_SNAPSHOT_ENTRIES | 56M| 11G| | 81840 (1)| 00:16:23 | Q1,04 | PCWP | |
Predicate Information (identified by operation id):
3 - access("AGG"."COMPANY_CODE"="DET"."COMPANY_CODE" AND "AGG"."ACCOUNT_NUMBER"=SUBSTR("DET"."ACCOUNT_NUMBER",1,5) AND
"AGG"."TRANSACTION_ID"="DET"."TRANSACTION_ID" AND "AGG"."TRANSACTION_ID_TYPE"="DET"."TRANSACTION_ID_TYPE")
7 - filter(ABS(SUM(SYS_OP_CSR(SYS_OP_MSR(SUM("Z"."AMOUNT"),MIN("Z"."ACCOUNTING_DATE")),0)))>=0.01)
15 - filter("USE"."ACCOUNTING_DATE"<TO_DATE(' 2010-04-22 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND "USE"."ACCOUNTING_DATE">=TO_DATE('
2010-04-21 00:00:00', 'syyyy-mm-dd hh24:mi:ss'))
16 - access("SE"."ACCOUNT_NUMBER"="AN"."ACCOUNT_NUMBER")
20 - filter("AN"."SUBLEDGER_TYPE"='AC' OR "AN"."SUBLEDGER_TYPE"='C')
29 - filter("ACCOUNTING_DATE"<TO_DATE(' 2010-04-22 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND "ACCOUNTING_DATE">=TO_DATE(' 2010-04-21
00:00:00', 'syyyy-mm-dd hh24:mi:ss'))
30 - access("DET"."ACCOUNT_NUMBER"="AN"."ACCOUNT_NUMBER")
34 - filter("AN"."SUBLEDGER_TYPE"='AC' OR "AN"."SUBLEDGER_TYPE"='C')
This query is failing due to TEMP issue (TEMP SPACE out of space)
My TEMP tablespace is 70GB and no one is using TEMP space while this query is in execution.
PGA=16 GB.
What i can see from execution plan is : Two large resultsets AGG (13Million) and DET (135 Million) is being joined HASH JOIN BUFFERED. Which is getting spilled to TEMP space causing TEMP outage.
Is there any way, i can re-write this query (probably using SUB QUERY FACTORING...WITH CLAUSE) so that reduce two times access to TEMP2_SL_SNAPSHOT_ENTRIES table. TEMP2_SL_SNAPSHOT_ENTRIES is 12 GB non partition table and i cannot use any other filter to restrict rows from this table.Adding more information here :
Inner sub query (Which forms DET-bottom)
select /*+ PARALLEL(det, 2) */ det.journal_entry_line_id, det.accounting_date, det.company_code, det.account_number, det.transaction_id,
decode(det.transaction_id_type, 'CollectionID', 'SettlementGroupID', det.transaction_id_type) transaction_id_type, det.amount, det.currency_code,
det.debit_or_credit, det.category, det.subcategory, det.reference1, det.reference1_type, det.reference2, det.reference2_type, det.gl_batch_id, det.marketplace_id,
det.cost_center, det.gl_product_line, det.location, det.project, det.sales_channel, det.created_by, det.creation_date, det.last_updated_by, det.last_updated_date
from financials.temp2_sl_snapshot_entries det,financials.account_numbers an
where det.account_number = an.account_number
and an.subledger_type in ('C', 'AC');
Plan hash value: 976020246
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | TQ |IN-OUT| PQ Distrib |
| 0 | SELECT STATEMENT | | 35M| 7514M| 163K (1)| 00:32:47 | | | |
| 1 | PX COORDINATOR | | | | | | | | |
| 2 | PX SEND QC (RANDOM) | :TQ10001 | 35M| 7514M| 163K (1)| 00:32:47 | Q1,01 | P->S | QC (RAND) |
|* 3 | HASH JOIN | | 35M| 7514M| 163K (1)| 00:32:47 | Q1,01 | PCWP | |
| 4 | BUFFER SORT | | | | | | Q1,01 | PCWC | |
| 5 | PX RECEIVE | | 21 | 210 | 2 (0)| 00:00:01 | Q1,01 | PCWP | |
| 6 | PX SEND BROADCAST | :TQ10000 | 21 | 210 | 2 (0)| 00:00:01 | | S->P | BROADCAST |
|* 7 | TABLE ACCESS FULL| ACCOUNT_NUMBERS | 21 | 210 | 2 (0)| 00:00:01 | | | |
| 8 | PX BLOCK ITERATOR | | 56M| 11G| 163K (1)| 00:32:45 | Q1,01 | PCWC | |
| 9 | TABLE ACCESS FULL | TEMP2_SL_SNAPSHOT_ENTRIES | 56M| 11G| 163K (1)| 00:32:45 | Q1,01 | PCWP | |
Predicate Information (identified by operation id):
3 - access("DET"."ACCOUNT_NUMBER"="AN"."ACCOUNT_NUMBER")
7 - filter("AN"."SUBLEDGER_TYPE"='AC' OR "AN"."SUBLEDGER_TYPE"='C')
Statistics
31 recursive calls
3 db block gets
1634444 consistent gets
1625596 physical reads
636 redo size
1803659818 bytes sent via SQL*Net to client
125054 bytes received via SQL*Net from client
11331 SQL*Net roundtrips to/from client
3 sorts (memory)
0 sorts (disk)
56645822 rows processedOther sub query (that forms AGG)
select /*+ PARALLEL(se, 2) */ company_code, substr(se.account_number, 1, 5) account_number,transaction_id,
decode(transaction_id_type, 'CollectionID', 'SettlementGroupID', transaction_id_type) transaction_id_type,se.amount,se.accounting_date
from financials.temp2_sl_snapshot_entries se,financials.account_numbers an
where se.account_number = an.account_number
and an.subledger_type in ('C', 'AC');
Plan hash value: 976020246
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | TQ |IN-OUT| PQ Distrib |
| 0 | SELECT STATEMENT | | 35M| 2012M| 163K (1)| 00:32:37 | | | |
| 1 | PX COORDINATOR | | | | | | | | |
| 2 | PX SEND QC (RANDOM) | :TQ10001 | 35M| 2012M| 163K (1)| 00:32:37 | Q1,01 | P->S | QC (RAND) |
|* 3 | HASH JOIN | | 35M| 2012M| 163K (1)| 00:32:37 | Q1,01 | PCWP | |
| 4 | BUFFER SORT | | | | | | Q1,01 | PCWC | |
| 5 | PX RECEIVE | | 21 | 210 | 2 (0)| 00:00:01 | Q1,01 | PCWP | |
| 6 | PX SEND BROADCAST | :TQ10000 | 21 | 210 | 2 (0)| 00:00:01 | | S->P | BROADCAST |
|* 7 | TABLE ACCESS FULL| ACCOUNT_NUMBERS | 21 | 210 | 2 (0)| 00:00:01 | | | |
| 8 | PX BLOCK ITERATOR | | 56M| 2701M| 162K (1)| 00:32:35 | Q1,01 | PCWC | |
| 9 | TABLE ACCESS FULL | TEMP2_SL_SNAPSHOT_ENTRIES | 56M| 2701M| 162K (1)| 00:32:35 | Q1,01 | PCWP | |
Predicate Information (identified by operation id):
3 - access("SE"."ACCOUNT_NUMBER"="AN"."ACCOUNT_NUMBER")
7 - filter("AN"."SUBLEDGER_TYPE"='AC' OR "AN"."SUBLEDGER_TYPE"='C')
Statistics
31 recursive calls
3 db block gets
1634444 consistent gets
1625596 physical reads
592 redo size
1803659818 bytes sent via SQL*Net to client
125054 bytes received via SQL*Net from client
11331 SQL*Net roundtrips to/from client
3 sorts (memory)
0 sorts (disk)
56645822 rows processed -
Is it possible to implement Recursive CTE query in MDX to Cube dataset?
I have data with hierarchical relationship like this:
Release -> Features -> PBI/Bugs -> Tasks/Test Case. I have two datasets Work Item and Work Item Linked to get this hierarchical information.
The data looks like this:
Something like if I pass a Release ID, I need to get all the children and sub-children also. Basically a report like this:
I did this by implementing a recursive CTE query with warehouse tables. But it takes more time to load. SO trying to find the possibility using MDX and querying the cube datasetsHello,
There is nothing stopping you from querying the cache to see what is in it. However, this will only take into account items that are already in the cache. If you need a query to return items that are potentially not in the cache, you need to query the database, have the query return keys, and then request those keys through Coherence - which will in turn pull the items from the database as needed.
Regards,
-Dave -
How do you get a Sub Query in a Mapping
Hi, I am wanting to know how or what the work around is for getting a Sub query in a join operator?
Its a really common place thing to do, I need to add an where exists or not exists type clause to one of my mapping joins.
Can someone please advise how this can be done using OWB.
Thanks,
Richard.I'm interested too.
Please help, I had own method to management iCal's event – new line, of 10.7 worked great – now is a little terrible for me :/ -
SELECT records larger than date specified in sub query
Dear All
Thank you for your attention.
I would like to select records larger than date specified in sub query
query should be something like the following
SELECT my_order_number, my_date, my_task
FROM MYTB
WHERE my_order_number IN order_no AND my_date > date (SELECT order_no, date FROM MySubQueryResult)
(it is incorrect)
Sub query result:
order_no | date
A1 | 2014-12-21 09:06:00
A2 | 2014-12-20 09:07:00
A3 | 2014-12-20 08:53:00
A4 | 2014-12-20 08:57:00
MYTB:
my_order_number | my_task | my_date
A1 | T1 | 2014-12-21 09:06:00
A1 | T2 | 2014-12-22 10:01:00
A2 | T1 | 2014-12-20 09:07:00
A3 | T2 | 2014-12-20 08:53:00
A3 | T4 | 2014-12-21 09:30:00
A3 | T8 | 2014-12-23 20:32:00
A4 | T6 | 2014-12-20 08:57:00
expected result:
my_order_number | my_task | my_date
A1 | T2 | 2014-12-22 10:01:00
A3 | T4 | 2014-12-21 09:30:00
A3 | T8 | 2014-12-23 20:32:00
Any ideas? Thanks.
swivanHi,
try this
SELECT my_order_number, my_date, my_task
FROM MYTB
WHERE my_order_number IN (SELECT order_no FROM MySubQueryResult)
AND my_date > (SELECT date FROM MySubQueryResult)
Alternatively, you can also make use of joins to achieve the same.
Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
Praveen Dsa | MCITP - Database Administrator 2008 |
My Blog | My Page
Dear Praveen Dsa
Thanks for your reply, but order_no and date are paired and related, cannot separate.
each order have its own date, so it is not working
Best Regards
swivan -
Queerish behavior of 'IN' sub query
Hii all,
I've encountered strange behavior of in clause.Here I'm providing a test case.
SQL> Create table r_dummy_1
2 as select object_name from user_objects
3 where rownum <= 10
4 ;
Table created.
SQL> select object_name from r_dummy_1;
OBJECT_NAME
CP_ST_CRITERIA
CP_ST_EXPENSE_CODE
CP_ST_FACILITIES
CP_ST_FACILITY_INFO
CP_ST_FAC_RESULT
CP_ST_INSTR_RESULT
CP_ST_RATINGS
CP_ST_RESULT_SET_DATE
CP_ST_RLTNSP_NAME
CP_ST_SIC_CODES
10 rows selected.I don't have a column named 'NAME' in my table 'R_DUMMY_1'.
But....
select *
from user_source
where name in(
select name
from r_dummy_1
)This query runs fine !!!!!!!!!!!!!!!
And when I individually run the inner query
SQL> select name
2 from r_dummy_1;
select name
ERROR at line 1:
ORA-00904: "NAME": invalid identifierIs this is a bug??Hi,
RGH wrote:
I thought the inner query executes first(Unlike correlated sub queries) and the outer picks the name matching in the result set.The optimizer decides whether the sub-query gets executed first or not.
Consider this query:
SELECT *
FROM scott.emp
WHERE 1 = 2
AND deptno IN (SELECT ...)
;The sub-query may not be run at all, because the optimizer "short-circuits". That is, it sees that the WHERE clause will resolve to FALSE regardless of what the sub-query produces, so it won't waste time running the sub-query.
Most of the time, assuming the sub-query is run, the results are as if the siub-query gets executed first, but in a correlated sub-query, at least part of the parent query has to be done earlier, because the values referenced in the sub-query have to be fetched before the sub-query can complete.
So in your query
select *
from user_source
where name in(
select name
from r_dummy_1
)The main query has to decide whether or not to include a row (let's say it's a row where name='PROC_X') from user_source, so it runs the sub-query. The sub-query runs, and produces a result set that includes the name from the main query, 'PROC_X'; control returns to the main query, and it compares the name to the results of the sub-query. The net effect is the same as:
select *
from user_source
where name in(name)For all I know, the optimizer may realize this, and re-write the query to actually perform the second version, never touchiung r_dummy_1 at all. -
How to get all rows that are returned in inner sub query of select statemen
If a sub query in select statement returns more than one row than how to get all those returned rows in the final
output of the query .It will be all right if all column's value repeat and that multiple output of inner query comes
in another column .
How to get that ?As Frank said, you likely want a join, and likely an outer join to replicate the select in the projection. Something like:
SELECT id,stat, section, USER_ID concerned_person
FROM table_all,
left join table2
on room_id = sectoion and
sur_role = 'r001'
WHERE section IN (SELECT code
FROM t_area
WHERE dept= 'p002')An alternative, depending on where and how you are using the statement would be something like:
SQL> WITH t AS (
2 select 1 id from dual union all
3 select 2 id from dual),
4 t1 as (
5 select 1 id, 'One' descr from dual union all
6 select 1, 'Un' from dual union all
7 select 1, 'Une' from dual)
8 SELECT t.id, CURSOR(SELECT t1.id, t1.descr from t1
9 WHERE t1.id = t.id)
10 FROM t;
ID CURSOR(SELECTT1.ID,T
1 CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
ID DESCR
1 One
1 Un
1 Une
2 CURSOR STATEMENT : 2
CURSOR STATEMENT : 2
no rows selectedJohn -
Can someone please help me with a sub query question?
I need to list a 3rd party contract and then a list of students who belong to that contract.
On the students segment of the listing I need to show students with student id, name, total credit hours,
total amount spent on tuition, total amount spent on books and total amount spent on misc.
This code has a query for the contract information and I get that just fine.
Then it has a query that gives me total credit hours and that works fine
then it has a query that gives me total amount spent on tuition and that works fine
but
when I add the next query to get total amount spent on books I get only the information for the contract, I don't get student stuff anymore.
I would really appreciate any guidance that you could give.
Thanks in advance, Bob Hohulski
DECLARE
l_conn utl_TCP.connection;
v_filehandle utl_file.file_type;
v_output varchar2(1000);
v_contract_id varchar2(9);
v_contract_addr1 varchar2(30);
v_contract_addr2 varchar2(30);
v_contract_city varchar2(20);
v_contract_stat varchar2(03);
v_contract_zip varchar2(10);
v_contract_name varchar2(60);
v_student_id varchar2(09);
v_student_first_name varchar2(15);
v_student_mid_name varchar2(15);
v_student_last_name varchar2(60);
v_last_out varchar2(20);
v_student_detail_code varchar2(04);
v_student_amount number(12,2);
v_student_ref_number varchar2(09);
v_credit_hrs number(7,2);
v_tuition_amount number(12,2);
v_books_amount number(12,2);
v_misc_amount number(12,2);
v_total_for_student number(12,2);
v_current_student varchar2(09);
v_sftregs_pidm varchar2(09);
v_tbraccd_pidm varchar2(09);
CURSOR c_sel_contract IS
SELECT DISTINCT spriden_id, spriden_last_name,
spraddr_street_line1, spraddr_street_line2,
spraddr_city, spraddr_stat_code, spraddr_zip
FROM spriden, spraddr
-- WHERE spriden_id = '&Enter_Id'
where spriden_id = 'T10474666'
AND spriden_pidm = spraddr_pidm
AND SPRIDEN_CHANGE_IND IS NULL;
CURSOR c_sel_student IS
SELECT DISTINCT spriden_id, spriden_first_name, spriden_mi, spriden_last_name,
sftregs_credit_hr,
tbraccd_amount,
sftregs_pidm,
tbraccd_pidm
FROM spriden, tbraccd, tbbcstu, sftregs
WHERE 559220 = tbbcstu_contract_pidm
AND spriden_pidm = tbraccd_pidm
AND spriden_pidm = tbbcstu_stu_pidm
AND spriden_pidm = sftregs_pidm
AND (sftregs_pidm, sftregs_credit_hr) IN
(SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
FROM sftregs, tbbcstu, spriden
WHERE sftregs_term_code = '201010'
AND sftregs_pidm = tbbcstu_stu_pidm
AND sftregs_pidm = spriden_pidm
GROUP BY sftregs_pidm)
AND (tbraccd_pidm, tbraccd_amount) IN
(SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
-- tuition
FROM tbraccd, tbbcstu, spriden
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'TU01' OR
tbraccd_detail_code = 'TU02' OR
tbraccd_detail_code = 'TU03' OR
tbraccd_detail_code = 'TU04')
AND tbraccd_pidm = tbbcstu_stu_pidm
AND tbraccd_pidm = spriden_pidm
GROUP BY tbraccd_pidm)
--this code works up to this point
--when I add the next query I get nothing
AND (tbraccd_pidm, tbraccd_amount) IN
(SELECT tbraccd_pidm, SUM(tbraccd_amount)
books
FROM tbraccd, tbbcstu
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'BKSU' OR
tbraccd_detail_code = 'BKCH')
AND tbraccd_pidm = tbbcstu_stu_pidm
GROUP BY tbraccd_pidm, tbraccd_amount)
--AND (tbraccd_pidm, tbraccd_amount) IN
-- (SELECT tbraccd_pidm, SUM(tbraccd_amount)
-- misc
-- FROM tbraccd, tbbcstu
-- WHERE tbraccd_term_code = '201010'
-- AND tbraccd_pidm = tbbcstu_stu_pidm
-- AND (tbraccd_detail_code = 'AUNA' OR
-- tbraccd_detail_code = 'OTPB')
-- GROUP BY tbraccd_pidm, tbraccd_amount)
--ORDER BY tbraccd_pidm, spriden_first_name, spriden_mi, spriden_last_name,
-- tbbcstu_sponsor_ref_number, sftregs_credit_hr;
ORDER BY tbraccd_pidm;
BEGIN
v_filehandle := utl_file.fopen(location => 'UTLFILE_MISAP9',
filename => 'ban_matrix.dat',
open_mode => 'w',
max_linesize => 32767);
OPEN c_sel_contract;
LOOP
DBMS_OUTPUT.PUT_LINE('looping');
FETCH c_sel_contract INTO v_contract_id, v_contract_name,
v_contract_addr1, v_contract_addr2,
v_contract_city, v_contract_stat,
v_contract_zip;
EXIT WHEN c_sel_contract%NOTFOUND;
v_output :=
nvl(rpad(v_contract_id,9),rpad(' ',9)) ||
' ' ||
nvl(rpad(v_contract_name,60),rpad(' ',60));
utl_file.put_line(v_filehandle,v_output);
v_output :=
nvl(rpad(v_contract_addr1, 30),rpad(' ',30)) ||
' ' ||
nvl(rpad(v_contract_addr2, 30),rpad(' ',30));
utl_file.put_line(v_filehandle,v_output);
v_output :=
nvl(rpad(v_contract_city, 20), rpad(' ',20)) ||
' ' ||
nvl(rpad(v_contract_stat, 3), rpad(' ',3)) ||
' ' ||
nvl(rpad(v_contract_zip, 10), rpad(' ',10));
utl_file.put_line(v_filehandle,v_output);
utl_file.new_line(v_filehandle);
OPEN c_sel_student;
LOOP
FETCH c_sel_student into v_student_id, v_student_first_name, v_student_mid_name,
v_student_last_name,
v_credit_hrs,
v_tuition_amount,
v_sftregs_pidm,
v_tbraccd_pidm;
-- v_books_amount, v_misc_amount;
EXIT WHEN c_sel_student%NOTFOUND;
v_last_out := substr(v_student_last_name, 1, 20);
v_output :=
nvl(rpad(v_student_id, 09),rpad(' ',09)) ||
' ' ||
nvl(rpad(v_student_first_name, 15),rpad(' ',15)) ||
nvl(rpad(v_student_mid_name, 15),rpad(' ',15)) ||
nvl(rpad(v_last_out, 20),rpad(' ',20)) ||
' ' ||
nvl(rpad(v_student_ref_number, 09),rpad(' ',09)) ||
' ' ||
v_credit_hrs ||
' ' ||
v_tuition_amount ||
-- v_books_amount ||
-- ' ' ||
-- v_misc_amount;
utl_file.put_line(v_filehandle,v_output);
END LOOP;
END LOOP;
--EXCEPTION
--WHEN OTHERS THEN
-- DECLARE
-- err_msg VARCHAR2(100);
-- BEGIN
-- err_msg := 'ERR- '||SUBSTR(SQLERRM, 1,100);
-- - utl_file.put_line(v_filehandle,err_msg);
--END;
utl_file.fclose(v_filehandle);
CLOSE c_sel_contract;
CLOSE c_sel_student;
--END AR_MATRIX_PROC;
END;run this original query
SELECT DISTINCT spriden_id,
spriden_first_name,
spriden_mi,
spriden_last_name,
sftregs_credit_hr,
tbraccd_amount,
sftregs_pidm,
tbraccd_pidm
FROM spriden, tbraccd, tbbcstu, sftregs
WHERE 559220 = tbbcstu_contract_pidm
AND spriden_pidm = tbraccd_pidm
AND spriden_pidm = tbbcstu_stu_pidm
AND spriden_pidm = sftregs_pidm
AND (sftregs_pidm, sftregs_credit_hr) IN (SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
FROM sftregs, tbbcstu, spriden
WHERE sftregs_term_code = '201010'
AND sftregs_pidm = tbbcstu_stu_pidm
AND sftregs_pidm = spriden_pidm
GROUP BY sftregs_pidm)
AND (tbraccd_pidm, tbraccd_amount) IN (SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
-- tuition
FROM tbraccd, tbbcstu, spriden
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'TU01' OR
tbraccd_detail_code = 'TU02' OR
tbraccd_detail_code = 'TU03' OR
tbraccd_detail_code = 'TU04')
AND tbraccd_pidm = tbbcstu_stu_pidm
AND tbraccd_pidm = spriden_pidm
GROUP BY tbraccd_pidm)
AND (tbraccd_pidm, tbraccd_amount) IN (SELECT tbraccd_pidm, SUM(tbraccd_amount) books
FROM tbraccd, tbbcstu
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'BKSU' OR
tbraccd_detail_code = 'BKCH')
AND tbraccd_pidm = tbbcstu_stu_pidm
GROUP BY tbraccd_pidm, tbraccd_amount)
ORDER BY tbraccd_pidm;then run this sub-query:
SELECT tbraccd_pidm, SUM(tbraccd_amount) books
FROM tbraccd, tbbcstu
WHERE tbraccd_term_code = '201010'
AND (tbraccd_detail_code = 'BKSU' OR
tbraccd_detail_code = 'BKCH')
AND tbraccd_pidm = tbbcstu_stu_pidm
GROUP BY tbraccd_pidm, tbraccd_amount)see if you have a matching tbraccd_pidm and tbraccd_amount between the two results. -
How to find out which sub query returns more than one row
Hi all,
Can any one give me clue ,how to find out which sub query returns more than one row in the following query .
/* Formatted on 2011/05/17 19:22 (Formatter Plus v4.8.8) */
SELECT a.*, ROWNUM AS rnm
FROM (SELECT DISTINCT '1' AS "Page View", ou.org_unit_name AS "Org",
prxm.mbr_idntfr AS "Beneficiary ID",
md.last_name
|| ', '
|| md.first_name AS "Beneficiary Name",
pci.idntfr AS "Tracking No.",
TO_CHAR (TRUNC (req.pa_rqst_date),
'MM/dd/yyyy'
) AS "Request Date",
sts.status_name AS "Status",
req.pa_rqst_sid AS "Request #",
prxm.mbr_sid AS "Mbr_sid",
TO_CHAR
(TRUNC (req.pa_revision_date),
'MM/dd/yyyy'
) AS "Last Updated",
TO_CHAR (psd.TO_DATE, 'MM/dd/yyyy') AS "TO_DATE",
prxpl.prvdr_lctn_iid AS "PRVDR_LCTN_IID",
pd.prvdr_sid AS "PRVDR_SID", 'Y' AS "State View",
DECODE
((SELECT DISTINCT pd.national_prvdr_idntfr
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid =
req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
0, (SELECT prxplo.prvdr_lctn_idntfr
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
NULL, (SELECT prxplo.prvdr_lctn_idntfr
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
(SELECT DISTINCT pd.national_prvdr_idntfr
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid =
req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR')
) AS "NPI/ID",
DECODE
((SELECT pd.org_bsns_name
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
NULL, (SELECT pd.last_name
|| ', '
|| pd.first_name
|| ' '
|| pd.middle_name
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
(SELECT pd.org_bsns_name
FROM pa_request_x_provider_location prxplo
WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
AND prxplo.oprtnl_flag = 'A'
AND prxplo.pa_prvdr_type_lkpcd = 'RR')
) AS "Prvdr Name",
TO_CHAR (psd.from_date,
'MM/dd/yyyy'
) AS "Srvc From Date",
TO_CHAR (req.validity_start_date,
'MM/DD/YYYY'
) AS "Due Date",
(fn_get_busniess_days (TRUNC (req.validity_start_date))
) AS "Days<br>Left",
req.pa_mode_type_lkpcd AS "Source",
TO_CHAR (TRUNC (wmdtl.rtng_date),
'MM/dd/yyyy'
) AS "Assigned On",
NVL (wmdtl.assigned_to_user_name,
'Not Assigned'
) AS "Assigned To",
req.org_unit_sid AS "OrgUnitSid",
TO_CHAR
(wmdtl.modified_date,
'MM/dd/yyyy hh24:mi:ss'
) AS "WTRD_MODIFIED_DATE",
TO_CHAR (wmdtl.rtng_date,
'MM/dd/yyyy'
) AS "WTRD_RTNG_DATE",
req.status_cid AS "PA_STATUS_CID",
TO_CHAR (req.modified_date,
'MM/dd/yyyy'
) AS "PA_REQ_MODIFIED_DATE",
prs.state_pa_srvc_type_code
AS "STATE_PA_SRVC_TYPE_CODE",
wmdtl.wm_pa_task_rtng_dtl_sid
AS "WM_TASK_RTNG_DTL_SID",
wmdtl.assigned_to_user_acct_sid
AS "WTRD_Assigned_to_user_acct_sid",
(fn_get_busniess_days (TRUNC (req.validity_start_date))
) AS "Days<br>LeftSort",
wmdtl.assigned_to_org_unit_sid
AS "WTRD_Assigned_to_OrgUntSid",
DECODE
((SELECT COUNT (*)
FROM pa_request_status prs
WHERE prs.pa_rqst_sid = req.pa_rqst_sid
AND prs.status_cid = 5
AND prs.oprtnl_flag = 'I'),
0, 'N',
'Y'
) AS "SHOW_UTILIZATION"
FROM pa_request req,
pa_certification_identifier pci,
status sts,
pa_request_x_member prxm,
wm_pa_task_routing_detail wmdtl,
pa_service_date psd,
org_unit ou,
pa_request_service prs,
pa_request_x_provider_location prxpl,
provider_location pl,
provider_detail pd,
provider p,
mbr_dmgrphc md
WHERE req.oprtnl_flag = 'A'
AND req.status_cid NOT IN
(20, 30, 70, 25, 80, 96, 85, 5, 97, 98, 101)
AND req.org_unit_sid IN
(3057, 3142, 3058, 3143, 3059, 3144, 3060, 3145,
3061, 3146, 3062, 3147, 3063, 3148, 3064, 3149,
3065, 3150, 3066, 3151, 3067, 3152, 3068, 3153,
3069, 3154, 3070, 3155, 3071, 3156, 3072, 3157,
3073, 3158, 3074, 3159, 3075, 3160, 3076, 3161,
3077, 3162, 3078, 3163, 3079, 3164, 3080, 3165,
3081, 3166, 3082, 3167, 3083, 3168, 3084, 3169,
3085, 3170, 3086, 3171, 3087, 3172, 3088, 3173,
3089, 3174, 3090, 3175, 3091, 3176, 3092, 3177,
3093, 3178, 3094, 3179, 3095, 3180, 3096, 3181,
3097, 3182, 3098, 3183, 3099, 3184, 3100, 3185,
3101, 3186, 3102, 3187, 3103, 3003, 75000104,
75000108, 2006, 75000103, 75000102, 75000113,
75000111, 75000109, 2001, 2009, 75000105,
75000107, 2004, 2010, 2013, 2014, 2005, 2011,
75000112, 2002, 1001, 2012, 75000106, 2007,
75000101, 2003, 75000110, 2008, 3001, 3002, 3019,
3104, 3020, 3105, 3021, 3106, 3022, 3107, 3023,
3108, 3024, 3109, 3025, 3110, 3026, 3111, 3027,
3112, 3028, 3113, 3029, 3114, 3030, 3115, 3031,
3116, 3032, 3117, 3033, 3118, 3034, 3119, 3035,
3120, 3036, 3121, 3037, 3122, 3038, 3123, 3039,
3124, 3040, 3125, 3041, 3126, 3042, 3127, 3043,
3128, 3044, 3129, 3045, 3130, 3046, 3131, 3047,
3132, 3048, 3133, 3049, 3134, 3050, 3135, 3051,
3136, 3052, 3137, 3053, 3138, 3054, 3139, 3055,
3140, 3056, 3141)
AND req.pa_rqst_sid = prs.pa_rqst_sid
AND prs.oprtnl_flag = 'A'
AND prs.pa_rqst_srvc_sid = psd.pa_rqst_srvc_sid
AND psd.oprtnl_flag = 'A'
AND req.pa_rqst_sid = pci.pa_rqst_sid
AND pci.oprtnl_flag = 'A'
AND req.pa_rqst_sid = prxm.pa_rqst_sid
AND prxm.oprtnl_flag = 'A'
AND md.oprtnl_flag = 'A'
AND md.status_cid = 2
AND TRUNC (SYSDATE) BETWEEN md.from_date AND md.TO_DATE
AND prxm.mbr_sid = md.mbr_sid
AND ou.org_unit_sid = req.org_unit_sid
AND ou.oprtnl_flag = 'A'
AND req.pa_rqst_sid = prxpl.pa_rqst_sid
AND prxm.pa_rqst_sid = prxpl.pa_rqst_sid
AND pci.pa_rqst_sid = prxm.pa_rqst_sid
AND pci.pa_rqst_sid = wmdtl.subsystem_task_sid
AND pci.pa_rqst_sid = prxpl.pa_rqst_sid
AND prxpl.pa_prvdr_type_lkpcd = 'RR'
AND prxpl.oprtnl_flag = 'A'
AND req.status_cid = sts.status_cid
AND sts.status_type_cid = 3
AND sts.oprtnl_flag = 'A'
AND prxpl.prvdr_lctn_iid = pl.prvdr_lctn_iid
AND p.prvdr_sid = pd.prvdr_sid
AND p.prvdr_sid = pl.prvdr_sid
AND pd.oprtnl_flag = 'A'
AND pd.status_cid = 2
AND TRUNC (SYSDATE) BETWEEN pd.from_date AND pd.TO_DATE
AND wmdtl.subsystem_task_sid = req.pa_rqst_sid
AND wmdtl.subsystem_lkpcd = 'PA'
AND wmdtl.oprtnl_flag = 'A'
AND req.pa_rqst_date > (SYSDATE - 365)
ORDER BY TO_DATE ("Request Date", 'MM/dd/yyyy hh24:mi:ss') DESC,
"Beneficiary Name" ASC) a
WHERE ROWNUM < 102;regards,
P Prakash
Edited by: BluShadow on 17-May-2011 15:01
added {noformat}{noformat} tags around the code833560 wrote:
Can any one give me clue ,how to find out which sub query returns more than one row in the following query .This is why smaller, simpler queries are easier to work with than huge ones - when something like this goes wrong smaller queries are much eaiser to debug. Unfortunately using smaller, easier-to-work with queries is not always an option
Ganesh is right - you will have to dissect the big query bit by bit until you find the offending subquery. If there is another way I would like to find out about it too.
The easiest way to do this is probably to use block comments to isolate parts of the query bit by bit until you find the offending part. If you carefully examine the subqueries you might be able to figure out which one is returning multiple rows without commenting everything
Good luck! -
How to use sub query in CAML in splist
hi,
want to know whether any sub query functionality can be achieved in splist/sp doc lib using CAML designer 2013/ query builder. also inner joins need to be implemented as pe rmy requirement.
if caml designer is not supported, whats the allternative way of doing this?
can LINQ to SP be used? if yes, can anyone pls roivde how to implement the same
help is appreciatedYou can use the let keyword to scope a variable containing the result of your subquery.
However, it depends on the LINQ provider as to whether or not it can understand the command.
For example, you can create the sample like this
var result = (from p in productInQuery
join o in orderInfoQuery on p.refNo equals o.refNo
join t in productOutQuery on p.no equals t.productInNo into productIn
from t in productIn.DefaultIfEmpty()
let dateOut = (from m in orderInfoQuery where m.refNo == t.refNo select m.processData).FirstOrDefault()
orderby o.processDate descending
select new
modelNo = x.modelNo,
qty = p.qty,
dateIn = o.processDate,
dateOut = dateOut
https://www.youtube.com/watch?v=N3K0h6GDwW4
For more info, check this
http://msdn.microsoft.com/en-us/library/ee539975.aspx -
Hi, I have two issues, here is my initial code:
select
cc.name_id_no
,cc.discover_date
,cc.cla_case_no
,max(rl.year_of_incident)Non_Loss_Past_5
,rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
Now a cla_case_no can map to several year_of_incident. I only want the cla_case_no that maps to the max year_of_incident ie There should only be a single cla_case_no corresponding to the max year_of_incident.
To get around this I did the following which is not very efficient and I'm hoping it can be improved:
select distinct z.cla_case_no from (
select
cc.name_id_no
,cc.discover_date
,cc.cla_case_no
,max(rl.year_of_incident)Non_MW_Loss_Past_5
,rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
) z
Now comes the second issue: The above is actually a subquery that will link to a bigger table via cla_case_no ccx
SELECT
ie ,(select distinct z.cla_case_no from (
select cc.name_id_no, cc.discover_date ,cc.cla_case_no, max(rl.year_of_incident)Non_MW_Loss_Past_5, rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
) z
where z.cla_case_no = ccx.cla_case_no
) Non_MW_Loss_Past_5
FROM etc
Now only certain cc.cla_case_no from the subquery will corresp to the ccx_cla_case_no from the main table and the other entries will be null.
What I require is that if the subquery returns a result that IS NOT NULL to return 'Y' ELSE 'N' instead of the varies cla_case_no's and (null) entries in the Non_MW_Loss_Past_5 column
Thanks!!!
Banner:
Oracle Database 11g Release 11.2.0.2.0 - 64bit Production
PL/SQL Release 11.2.0.2.0 - Production
"CORE 11.2.0.2.0 Production"
TNS for Linux: Version 11.2.0.2.0 - Production
NLSRTL Version 11.2.0.2.0 - ProductionHi,
It looks like you have another copy of this question:
Case Statement and sub query
That's probably not your fault, but you should mark the other copy as "Answered" right away, and then you'll only have to look for replies in one place.
885178 wrote:
... Now a cla_case_no can map to several year_of_incident. I only want the cla_case_no that maps to the max year_of_incident ie There should only be a single cla_case_no corresponding to the max year_of_incident.If you know there will only be one, then you can use LAST, and you don't need GrOUP BY
To get around this I did the following which is not very efficient and I'm hoping it can be improved:
select distinct z.cla_case_no from (
select
cc.name_id_no
,cc.discover_date
,cc.cla_case_no
,max(rl.year_of_incident)Non_MW_Loss_Past_5
,rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
) zHere's one way:
SELECT MIN (cla_case_no) KEEP (DENSE_RANK LAST ORDER BY r1.year_of_incident)
AS latest_cla_case_no
FROM cla_case cc
, rbn_loss rl
WHERE cc.name_id_no = rl.customer_no
AND rl.year_of_incident > TRUNC (cc.discover_date) - 1095
AND rl.year_of_incident < TRUNC (cc.discover_date)
AND rl.type_of_loss < 1000
AND rl.timestamp < TRUNC (cc.discover_date)
AND cc.question_class IN (20, 25)
;If you'd post some sample data (CREATE TABLE and INSERT statements) and the results you want from that data, then I could test this.
Now comes the second issue: The above is actually a subquery that will link to a bigger table via cla_case_no ccx
SELECT
ie ,(select distinct z.cla_case_no from (
select cc.name_id_no, cc.discover_date ,cc.cla_case_no, max(rl.year_of_incident)Non_MW_Loss_Past_5, rl.timestamp
from cla_case cc, rbn_loss rl
where cc.name_id_no = rl.customer_no
and rl.year_of_incident < trunc(cc.discover_date)
and rl.type_of_loss < 1000
and rl.timestamp < trunc(cc.discover_date)
and (cc.question_class = 20
or cc.question_class = 25)
and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
--and (trunc(cc.discover_date) <> (rl.year_of_incident))
group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
) z
where z.cla_case_no = ccx.cla_case_no
) Non_MW_Loss_Past_5
FROM etc
Now only certain cc.cla_case_no from the subquery will corresp to the ccx_cla_case_no from the main table and the other entries will be null.
What I require is that if the subquery returns a result that IS NOT NULL to return 'Y' ELSE 'N' instead of the varies cla_case_no's and (null) entries in the Non_MW_Loss_Past_5 column
NVL2 (x, 'Y', 'N')returns 'Y' if x is NULL, and it returns 'N' if x is not NULL. X can be a scalar sub-query:
NVL2 ((SELECT ...), 'Y', 'N')You could also use an EXISTS sub-query:
CASE
WHEN EXISTS (SELECT ...)
THEN 'Y'
ELSE 'N'
END -
Hi,
Can we use order by clause in Sub query?
While using the order by clause, I am getting the "missing expression error" . If I remove order by clause query executing fine.
Here is my query:
select *
from emp_mstr
where emp_no in(select
emp_no
from emp_mstr
order by branch_no);
Thanks & Regards,
MahiMay be you miss some required spaces also, other than wrong use of ORDER BY
select *
from emp_mstr
where emp_no in
( select e2.emp_no
from emp_mstr e2
-- order by e2.branch_no
);Why do you want to ORDER BY in the subquery, which you use with IN clause? That will not make any difference in the result..Means the result you get with ORDER BY will be same as without that.. And in this case, ORDER by is a unncessary overhead.. And Ordering is very costly..
And why do you want to have the IN clause at all in your query? You are referring the same tables in the main query and sub query..
The below will give the same result
select *
from emp_mstr
where emp_no is not nullIf you want to use another table in the subquery, always use aliasess...
select *
from emp_mstr
where emp_no in
( select e2.emp_no
from emp_mstr2 e2
-- order by e2.branch_no
); -
Dear All,
Based on below image show that the error message, As i know is aggregation problem in sub query, May i know how to solve it ? thank you.Please have enough Netiquette to post DDL and not pictures.
Think about how absurd "MIN(AVG(AGE)))" on two levels. No, really, you can see that this is absurd if you have any concept of sets.
No competent programmer would put age in a column. It is a dynamic value! The constant is birith_date. Age is computed in the presentation layers.
--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 -
Possibility of launch of a sub query in a query
Hi developers,
I have an urgent problem! I have created a query to calculate with a formula an indicator but if I effectue a drill down for customer I have a correct result while when I drill down for country the rows compact the value and the result change in wrong. Is There the possibility or a functionality who allows the launch of a query with selection on another query.
Have Someone a solution to this problem ?
Thanks,
Domeico
Message was edited by: Domenico MantiHi Domeico,
I'm not sure I understand your problem correctly, but instead of launching a sub query in a query I would recommend to check, whether a variable with replacement path (reference to characteristic (constant 1)) might solve your problem.
http://help.sap.com/saphelp_nw04/helpdata/en/03/6ba03cc24efd1de10000000a114084/frameset.htm
and
http://help.sap.com/saphelp_nw04/helpdata/en/ca/5f9ac61a205a459d0e7ef313d10321/frameset.htm
Heike
Maybe you are looking for
-
AP:selected payment schedules report "Credit reduces payment amount below
Hi all: I have a PPR reject one Debit memo with reason "Credit reduces payment amount below zero" at first and shows out in report "selected payment schedules report" as Unselected Scheduled Payments. PPR Pay through date: 28-Nov-2011 Issued Debit Me
-
Problem of accuracy when sync with mac OS
When I sync my Curve 8520 with my mac, the time of a meting changes. If for example I write a meeting in my phone between 01:00 to 02:00, it will be marked on my computer between 02:00 to 03:00. Another problem: a meeting that will last one all day d
-
Hi Experts, Can any one help me to find the Purchase Order Release date. I.e. in which table i can get the PO rel. Date. Thanks in Adv. AK null
-
Adding Oracle App Server 10.1.3 under 10.1.2 SSO
We are planning to install a new instance of the Oracle Application Server 10.1.3 to host some applications. But our current Portal and SSO/OID installation is Oracle App. Server 10.1.2. Is it OK to register 10.1.3 with SSO/OID of 10.1.2? Any help wi
-
Cascading lists drop downs in SharePoint Designer (no server-side code) without postback
I've created cascading drop downs populated from SharePoint lists, by following this post by Lars in SharePoint designer without using code, it works fine, my issue is that the secondary drop down only populates if the main drop down causes auto-post