Sub-query question, looking up value within a query
I have a situation to lookup prior period value within the same query. I tried to use a sub-query but getting a syntax error:
SELECT [VALUE-BAND_ACCT].GLSeq, [VALUE-BAND_ACCT].NUM_SITES, [VALUE-BAND_ACCT].SGMNT1,
[VALUE-BAND_ACCT].SGMNT2, [VALUE-BAND_ACCT].LOB$, [VALUE-BAND_ACCT].PERIOD, [VALUE-BAND_ACCT].RECUR, [VALUE-BAND_ACCT].PROMOTED, [VALUE-BAND_ACCT].COMB_REV_GRS, [VALUE-BAND_ACCT].COMB_REV_NET, [VALUE-BAND_ACCT].ARPSg_ACCT, [VALUE-BAND_ACCT].ARPSn_ACCT,
[VALUE-BAND_ACCT].COMB_VALUE_BAND,
(SELECT [VALUE-BAND_ACCT].COMB_VALUE_BAND
FROM VALUE-BAND_ACCT
WHERE [VALUE-BAND_ACCT].PERIOD = DateSerial(Year([VALUE-BAND_ACCT].PERIOD), Month([VALUE-BAND_ACCT].PERIOD)-1, 1)) AS PRIOR_VALUE_BAND
FROM VALUE-BAND_ACCT;
Appreciating help.
Try this:
SELECT [VALUE-BAND_ACCT].GLSeq, [VALUE-BAND_ACCT].NUM_SITES, [VALUE-BAND_ACCT].SGMNT1,
[VALUE-BAND_ACCT].SGMNT2, [VALUE-BAND_ACCT].LOB$, [VALUE-BAND_ACCT].PERIOD,
[VALUE-BAND_ACCT].RECUR, [VALUE-BAND_ACCT].PROMOTED, [VALUE-BAND_ACCT].COMB_REV_GRS,
[VALUE-BAND_ACCT].COMB_REV_NET, [VALUE-BAND_ACCT].ARPSg_ACCT,
[VALUE-BAND_ACCT].ARPSn_ACCT, [VALUE-BAND_ACCT].COMB_VALUE_BAND,
[VALUE-BAND_ACCT_1].COMB_VALUE_BAND AS PRIOR_VALUE_BAND
FROM [VALUE-BAND_ACCT] INNER JOIN [VALUE-BAND_ACCT] AS [VALUE-BAND_ACCT_1]
ON [VALUE-BAND_ACCT].GLSeq = [VALUE-BAND_ACCT_1].GLSeq AND
[VALUE-BAND_ACCT].[LOB$] = [VALUE-BAND_ACCT_1].[LOB$]
WHERE [VALUE-BAND_ACCT_1].PERIOD =
DateSerial(Year([VALUE-BAND_ACCT].PERIOD), Month([VALUE-BAND_ACCT].PERIOD)-1, 1)
or
SELECT [VALUE-BAND_ACCT].GLSeq, [VALUE-BAND_ACCT].NUM_SITES, [VALUE-BAND_ACCT].SGMNT1,
[VALUE-BAND_ACCT].SGMNT2, [VALUE-BAND_ACCT].LOB$, [VALUE-BAND_ACCT].PERIOD,
[VALUE-BAND_ACCT].RECUR, [VALUE-BAND_ACCT].PROMOTED, [VALUE-BAND_ACCT].COMB_REV_GRS,
[VALUE-BAND_ACCT].COMB_REV_NET, [VALUE-BAND_ACCT].ARPSg_ACCT,
[VALUE-BAND_ACCT].ARPSn_ACCT, [VALUE-BAND_ACCT].COMB_VALUE_BAND,
[VALUE-BAND_ACCT_1].COMB_VALUE_BAND AS PRIOR_VALUE_BAND
FROM [VALUE-BAND_ACCT] INNER JOIN [VALUE-BAND_ACCT] AS [VALUE-BAND_ACCT_1]
ON [VALUE-BAND_ACCT].GLSeq = [VALUE-BAND_ACCT_1].GLSeq AND
[VALUE-BAND_ACCT].[LOB$] = [VALUE-BAND_ACCT_1].[LOB$] AND
[VALUE-BAND_ACCT_1].PERIOD =
DateSerial(Year([VALUE-BAND_ACCT].PERIOD), Month([VALUE-BAND_ACCT].PERIOD)-1, 1)
Regards, Hans Vogelaar (http://www.eileenslounge.com)
Similar Messages
-
How to write multi row sub query with the row containing range of values?
Hi all,
I have to include a column which contains weight ranges and it should come fom table called "report_range_parameters"
The following query will reutrn those weight ranges.
select report_parameter_min_value || ' -> ' || report_parameter_max_value
from report_range_parameters
WHERE report_range_parameters.report_parameter_id = 2359
and report_range_parameters.report_parameter_group = 'GVW_GROUP'
and report_range_parameters.report_parameter_name = 'GVW_NAME'
The below query should return the values group by those weight ranges.
How could I write that sub query?
select SUM(NVL("Class 0", 0)) "Class 0" ,
SUM(NVL("Class 1", 0)) "Class 1" ,
SUM(NVL("Class 2", 0)) "Class 2" ,
SUM(NVL(" ", 0)) "Total"
FROM (
SELECT report_data.bin_start_date_time start_date_time,
SUM(DECODE(report_data.gvw, 0, report_data.gvw_count, 0)) "Class 0" ,
SUM(DECODE(report_data.gvw, 1, report_data.gvw_count, 0)) "Class 1" ,
SUM(DECODE(report_data.gvw, 2, report_data.gvw_count, 0)) "Class 2" ,
SUM(NVL(report_data.gvw_count, 0)) " "
FROM report_data
GROUP BY report_data.bin_start_date_time
) results
RIGHT OUTER JOIN tmp_bin_periods
ON results.start_date_time >= tmp_bin_periods.bin_start_date_time
AND results.start_date_time < tmp_bin_periods.bin_end_date_time
GROUP BY tmp_bin_periods.bin_start_date_time,
tmp_bin_periods.bin_end_date_time Thanks.
Edited by: user10641405 on Jun 15, 2009 3:14 PM
Edited by: user10641405 on Jun 15, 2009 3:17 PMHi,
Assuming the following 4 things:
(1) report_range_parameters contains data like this, from your [previous thread|http://forums.oracle.com/forums/message.jspa?messageID=3541079#3541079]
id group name min_value max_value
1 gvw_group gvw_name 0 5
2 gvw_group gvw_name 5 10
3 gvw_group gvw_name 10 15(2) max_value is actually outside the range (that is, a value of exactly 5.000 is counted in the '5->10' range, not the '0->5' range)
(3) the range has to match some column x that is in one of the tables in your main query
(4) You want to add that column x to the GROUP BY clause
then you shopuld do somehting like this:
select SUM(NVL("Class 0", 0)) "Class 0" ,
SUM(NVL("Class 1", 0)) "Class 1" ,
SUM(NVL("Class 2", 0)) "Class 2" ,
SUM(NVL(" ", 0)) "Total"
, report_parameter_min_value || ' -> ' || report_parameter_max_value AS weight_range -- New
FROM (
SELECT report_data.bin_start_date_time start_date_time,
SUM(DECODE(report_data.gvw, 0, report_data.gvw_count, 0)) "Class 0" ,
SUM(DECODE(report_data.gvw, 1, report_data.gvw_count, 0)) "Class 1" ,
SUM(DECODE(report_data.gvw, 2, report_data.gvw_count, 0)) "Class 2" ,
SUM(NVL(report_data.gvw_count, 0)) " "
FROM report_data
GROUP BY report_data.bin_start_date_time
) results
RIGHT OUTER JOIN tmp_bin_periods
ON results.start_date_time >= tmp_bin_periods.bin_start_date_time
AND results.start_date_time < tmp_bin_periods.bin_end_date_time
LEFT OUTER JOIN report_range_parameters -- New
ON x >= report_parameter_min_value -- New
AND x < report_parameter_max_value -- New
AND report_range_parameters.report_parameter_id = 2359 -- New
and report_range_parameters.report_parameter_group = 'GVW_GROUP' -- New
and report_range_parameters.report_parameter_name = 'GVW_NAME' -- New
GROUP BY tmp_bin_periods.bin_start_date_time,
tmp_bin_periods.bin_end_date_time
, x -- New -
Too many values issues in sub query
Hi ALL,
I have a sql query like below :
SELECT A,B,C,(SELECT D,E,F,G FROM ABC,DEF,... WHERE ABC.ID=DEF.ID......) NAME FROM TEST1,TEST2 WHERE .......
So my subquery is throwing an error as too many values so how can i get column values in my subquery through single select statement.
Please help me on thisuser13424229 wrote:
Hi ALL,
I have a sql query like below :
SELECT A,B,C,(SELECT D,E,F,G FROM ABC,DEF,... WHERE ABC.ID=DEF.ID......) NAME FROM TEST1,TEST2 WHERE .......
So my subquery is throwing an error as too many values so how can i get column values in my subquery through single select statement.Select Sub-Query can Select only 1 Column and 1 Record at a Time.
If you wish to cater it, you will have to write the same select statement for all the columns individually. viz. D, E, F, G shall amount to 4 individual selects in your main select statement. -
Passing values dynamically Froman 'INLINE Query' to a 'SUB QUERY'
If I am using an line query which uses a SELF JOIN subquery
how can I pass the values from the Inline Query to Subquery ?
Is this possible?
SQL...Code
and Inline Queries..
(select count(*) 'PrimaryISIN'
from instrument ins,
instrument_xref insx
where ins.id_inst = insx.id_inst
and insx.flg_active = 'Y'
and ins.id_source ='MF'
and ins.flg_primary_listing = 'Y'
and ins.flg_active = 'Y'
and insx.id_inst_xref = ( select DISTINCT a.id_inst_xref
from instrument_xref a,
instrument_xref b
where b.id_inst_xref ='B0DV8Y9'
and b.id_inst = a.id_inst
and b.id_inst_xref_type in ('SE','IS')
and a.id_inst_xref = 'GB00B03MLX29'
)PISIN2
I am hardcoding the id_inst_xref is the SELF JOIN? Can these be passed dynamically from
the INLINE Query which is invoking the SUB QUERY?Hi, The hardcoded values entered in the SELF JOIN run fine.
Now,I need to pass values dynamically from the INLINE query.
How do I do that?
Thanks -
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. -
Oracle 8i - PL/SQL sub query not working in PROC, but works ins SQL
I have read about certain things not working in 8i and I think this is one of them, but I was wondering if anyone had a work around. In the place of the SELECT SYSDATE FROM DUAL, I have a table look up, where I am going to look up the OCN of the corresponding VENDOR_ID ( a column in the original query ). I am doing it in a decode statement because if the first condition in the decode statement is met, that's it. But if not, it needs to look up the OCN number in this other table. Simple enough, conceptually. I thought of a view but that necessitates a SELECT statement, too. Anyway, here is the code with the appropriate text bolded:
CREATE OR REPLACE PROCEDURE tstINS_RATE_ROUTE_RECORDS_PROC (GET_CUR_PERIOD IN DATE) IS
CUR_PERIOD DATE;
BEGIN
CUR_PERIOD := GET_CUR_PERIOD;
Insert into RATE_ROUTE (
CVBI_KEY
, VENDOR_ID
, OCN
, ST_CD
, PERIOD
, MDFY_DT )
Select
C.CVBI_KEY
, C.VENDOR_ID
<b>, decode( c.send_lca, 'YES', 'XXX', (SELECT SYSDATE FROM DUAL) )</b>
, decode( c.send_lca, 'YES', 'XX', SUBSTR(C.ZLOC,5,2) )
, CUR_PERIOD
, TO_CHAR(SYSDATE)
FROM
rpt_ds1_cnt_cat c
, cogs_resource cr
, cogs_t1activity ct1
, rpt_ds1_aloc_zloc_reverse_vw az
where (C.CVBI_KEY = CR.CVBI_KEY (+)
and CR.PERIOD = CUR_PERIOD)
AND (C.CVBI_KEY = CT1.CVBI_KEY (+)
and CT1.PERIOD = CUR_PERIOD)
and (az.master_route_name=c.aloc||'-'||c.zloc OR az.reversed=c.aloc||'-'||c.zloc)
END; -- INS_RATE_ROUTE_RECORDS_PROChave read about certain things not working in 8i and I think this is one of them,Yes as I said scalar sub-queries were also not recognized within PL/SQL in 8i.
Re: PLS-00103: Encountered the symbol "SELECT" when expecting one of the fo
I was wondering if anyone had a work around.Write a function that returns the value. You may incur a performance penalty from a context switch to PL/SQL, but it may be balanced by the decode optimization you are attempting. -
Get the two rows of customer with same amount value within consecutive year
Hi,
Below are sample data, what I would like to do is pull the customer along with their two finance details that have the same amount within the two consecutive year. Please note that there are many customers and not all customers are have these criteria, so the query should not include those customers.
Like in my sample data the result should be:
(first row)
165321 John King Magazine 01/03/2007 30/03/2011 10/02/2009 180.00
(second row)
165321 John King Magazine 01/03/2007 30/03/2011 06/12/2008 180.00
Customer Table:
ID Name Product Start Delivery End Delivery
165321 John King Magazine 01/03/2007 30/03/2011
165322 Bryan Lee Magazine 15/04/2002 30/04/2011
Finance Table:
ID Invoice Date USD Amount
165321 10/02/2009 180.00
165321 10/02/2009 120.00
165321 06/12/2008 180.00
165321 20/05/2007 99.00
165321 12/03/2007 150.00
165321 07/03/2007 180.00
165322 01/01/2003 124.00
165322 30/05/2002 160.00
165322 20/04/2002 99.00
Thank you..Hi,
Depending on your exact requirements, you can do something like this:
WITH got_this_yr AS
SELECT id
, MIN (invoice_date) AS invoice_date
, usd_amount
, EXTRACT (YEAR FROM invoice_date) AS this_yr
FROM finance
-- WHERE ... -- any filtering goes here
GROUP BY id
, usd_amount
, EXTRACT (YEAR FROM invoice_date)
, got_neighbor_values AS
SELECT id
, invoice_date
, usd_amount
, this_yr
, LAG (this_year) OVER ( PARTITION BY id
, usd_amount
ORDER BY this_year
) AS prev_year
, LEAD(this_year) OVER ( PARTITION BY id
, usd_amount
ORDER BY this_year
) AS next_year
FROM got_this_yr
SELECT n.id
, c.name
, c.product
, c.start_delivery
, c.end_delivery
, n.invoice_date
, n.usd_amount
FROM got_neighbor_values n
JOIN customer c ON c.id = n.id
WHERE n.this_year IN ( n.prev_year + 1
, n.next_year - 1
ORDER BY n.id
, n.usd_amount
, n.invoice_date
;If you'd care to post CREATE TABLE and INSERT statements for the sample data, then I could test this.
This used the analytic LAG and LEAD functions to find the previous and next years when the same amount occurred with the same id. Since we want to use this value in a WHERE clause, it has to be computed in a sub-query (got_neighbor_vlues) first; analytic functions are always computed after the WHERRE clause is applied.
In the case of the very first year, LAG will return NULL, and in the case of the very last year, LEAD will return NULL. That's okay for our purposes; we just need something such that the WHERE clause of the main query will be TRUE if and only if one of the adjacent rows was a consecutive year.
Why don't you want a row for 2007 in the results? It looks like the same customer had the exact same amount in 2007, 2008 and 2009.
What happens if the same customer has the exact same amount 2 (or more) times in the same calendar year? The query above uses the earliest one in each year, and ignores the others. If that's not what you want, then post the results you do want
Edited by: Frank Kulash on Nov 15, 2010 10:36 AM
Included cutomer table -
Trying to get multiple cell values within a geometry
I am provided with 3 tables:
1 - The GeoRaster
2 - The geoRasterData table
3 - A VAT table who's PK is the cell value from the above tables
Currently the user can select a point in our application and by using the getCellValue we get the cell value which is the PK on the 3rd table and this gives us the details to return to the user.
We now want to give the worst scenario within a given geometry or distance. So if I get back all the cell values within a given geometry/distance I can then call my other functions against the 3rd table to get the worst scores.
I had a conversation open for this before where JeffreyXie had some brilliant input, but it got archived while I was waiting on Oracle to resolve a bug (about 7 months)
See:
Trying to get multiple cell values within a geometry
If I am looking to get a list of cell values that interact with my geometry/distance and then loop through them, is there a better way?
BTW, if anybody wants to play with this functionality, it only seems to work in 11.2.0.4.
Below is the code I was using last, I think it is trying to get the cell values but the numbers coming back are not correct, I think I am converting the binary to integer wrong.
Any ideas?
CREATE OR REPLACE FUNCTION GEOSUK.getCellValuesInGeom_FNC RETURN VARCHAR2 AS
gr sdo_georaster;
lb blob;
win1 sdo_geometry;
win2 sdo_number_array;
status VARCHAR2(1000) := NULL;
CDP varchar2(80);
FLT number := 0;
cdl number;
vals varchar2(32000) := null;
VAL number;
amt0 integer;
amt integer;
off integer;
len integer;
buf raw(32767);
MAXV number := null;
r1 raw(1);
r2 raw(2);
r4 raw(200);
r8 raw(8);
MATCH varchar2(10) := '';
ROW_COUNT integer := 0;
COL_COUNT integer := 0;
ROW_CUR integer := 0;
COL_CUR integer := 0;
CUR_XOFFSET integer := 0;
CUR_YOFFSET integer := 0;
ORIGINY integer := 0;
ORIGINX integer := 0;
XOFF number(38,0) := 0;
YOFF number(38,0) := 0;
BEGIN
status := '1';
SELECT a.georaster INTO gr FROM JBA_MEGARASTER_1012 a WHERE id=1;
-- first figure out the celldepth from the metadata
cdp := gr.metadata.extract('/georasterMetadata/rasterInfo/cellDepth/text()',
'xmlns=http://xmlns.oracle.com/spatial/georaster').getStringVal();
if cdp = '32BIT_REAL' then
flt := 1;
end if;
cdl := sdo_geor.getCellDepth(gr);
if cdl < 8 then
-- if celldepth<8bit, get the cell values as 8bit integers
cdl := 8;
end if;
dbms_lob.createTemporary(lb, TRUE);
status := '2';
-- querying/clipping polygon
win1 := SDO_GEOM.SDO_BUFFER(SDO_GEOMETRY(2001,27700,MDSYS.SDO_POINT_TYPE(473517,173650.3, NULL),NULL,NULL), 10, .005);
status := '1.2';
sdo_geor.getRasterSubset(gr, 0, win1, '1',
lb, win2, NULL, NULL, 'TRUE');
-- Then work on the resulting subset stored in lb.
status := '2.3';
DBMS_OUTPUT.PUT_LINE ( 'cdl: '||cdl );
len := dbms_lob.getlength(lb);
cdl := cdl / 8;
-- make sure to read all the bytes of a cell value at one run
amt := floor(32767 / cdl) * cdl;
amt0 := amt;
status := '3';
ROW_COUNT := (WIN2(3) - WIN2(1))+1;
COL_COUNT := (WIN2(4) - WIN2(2))+1;
--NEED TO FETCH FROM RASTER
ORIGINY := 979405;
ORIGINX := 91685;
--CALCUALATE BLOB AREA
YOFF := ORIGINY - (WIN2(1) * 5); --177005;
XOFF := ORIGINX + (WIN2(2) * 5); --530505;
status := '4';
--LOOP CELLS
off := 1;
WHILE off <= LEN LOOP
dbms_lob.read(lb, amt, off, buf);
for I in 1..AMT/CDL LOOP
if cdl = 1 then
r1 := utl_raw.substr(buf, (i-1)*cdl+1, cdl);
VAL := UTL_RAW.CAST_TO_BINARY_INTEGER(R1);
elsif cdl = 2 then
r2 := utl_raw.substr(buf, (i-1)*cdl+1, cdl);
val := utl_raw.cast_to_binary_integer(r2);
ELSIF CDL = 4 then
IF (((i-1)*cdl+1) + cdl) > len THEN
r4 := utl_raw.substr(buf, (i-1)*cdl+1, (len - ((i-1)*cdl+1)));
ELSE
r4 := utl_raw.substr(buf, (i-1)*cdl+1, cdl+1);
END IF;
if flt = 0 then
val := utl_raw.cast_to_binary_integer(r4);
else
val := utl_raw.cast_to_binary_float(r4);
end if;
elsif cdl = 8 then
r8 := utl_raw.substr(buf, (i-1)*cdl+1, cdl);
val := utl_raw.cast_to_binary_double(r8);
end if;
if MAXV is null or MAXV < VAL then
MAXV := VAL;
end if;
IF i = 1 THEN
VALS := VALS || VAL;
ELSE
VALS := VALS ||'|'|| VAL;
END IF;
end loop;
off := off+amt;
amt := amt0;
end loop;
dbms_lob.freeTemporary(lb);
status := '5';
RETURN VALS;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20001, 'GENERAL ERROR IN MY PROC, Status: '||status||', SQL ERROR: '||SQLERRM);
END;Hey guys,
Zzhang,
That's a good spot and as it happens I spotted that and that is why I am sure I am querying that lob wrong. I always get the a logic going past the total length of the lob.
I think I am ok using 11.2.0.4, if I can get this working it is really important to us, so saying to roll up to 11.2.0.4 for this would be no problem.
The error in 11.2.0.3 was an internal error: [kghstack_underflow_internal_3].
Something that I think I need to find out more about, but am struggling to get more information on is, I am assuming that the lob that is returned is all cell values or at lest an array of 4 byte (32 bit) chunks, although, I don't know this.
Is that a correct assumption or is there more to it?
Have either of you seen any documentation on how to query this lob?
Thanks -
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 -
I have a doubt with the use of sub-queries. I am using a query like as below & it is giving me expected result:-
SELECT ISS.item_type_id,count(1) + (select sum(invoiced_qty) from ppbs_invoice_detail where
trunc(created_date) between '01-jul-05' and '04-jul-05' and item_type_id=ISS.item_type_id) qty
FROM ppbs_INV_SIM_SERIAL ISS
WHERE INSTR('ROAAIT',STATUS)>0
AND INSTR('NU0NU1NU2NU3SC0',CITY_CODE) =0
and ISS.item_type_id in ('SM17')
group by ISS.item_type_id --
I will re-write above query & i have been using queries like :-
SELECT ISS.item_type_id,count(1) qty
FROM ppbs_INV_SIM_SERIAL ISS
WHERE INSTR('ROAAIT',STATUS)>0
AND INSTR('NU0NU1NU2NU3SC0',CITY_CODE) =0
and ISS.item_type_id in ('SM17') and item_type_id in
(select item_type_id from ppbs_invoice_detail where
trunc(created_date) between '01-jul-05' and '04-jul-05' and item_type_id=ISS.item_type_id)
group by ISS.item_type_id
my doubt here is that the sub-query in the first query is coming before i use the table 'ppbs_inv_sim_serial ISS' whereas in the second query, the table use 'ppbs_inv_sim_serial ISS' is coming before the sub-query use. I have been using queries where table name is defined before the sub-query.
I hope, my question is clear. Please help in solving the doubt.
Regards.I don't see a problem with the table aliasing that you seem to doubt, but your first query won't run. I boiled the thing down to basics: SQL>create table t1 (one number, val_1 number );
Table created.
SQL>create table t2 (one number, val_2 number );
Table created.
SQL>insert into t1 values (1,1);
1 row created.
SQL>insert into t2 values (1,2);
1 row created.
SQL>select a.one, count(1) + ( select sum(val_2) from t2 where t2.one = a.one) qty
2 from t1 a
3 group by one;
select a.one, count(1) + ( select sum(val_2) from t2 where t2.one = a.one) qty
ERROR at line 1:
ORA-00979: not a GROUP BY expression
SQL>
SQL>select a.one, count(1) qty
2 from t1 a
3 where a.one in ( select one from t2 where one = a.one)
4 group by one;
ONE QTY
1 1It's superfluous to "where a.one in ( select.. where = a.one) but that's your code basically. I would just do "=" -
Query Performance and Result Set Query/Sub-Query
Hi,
I have an infoset with as many as <b>15 joins</b> with different ODS and Master Data..<b>The ODS are quite huge with 20 million, 160 million records)...</b>Its taking a lot of time even for a few days and need to get atleast 3 months data in a reasonable amount of time....
Could anyone please tell me whether <b>Sub-Query or Result Set Query have to be written against the same InfoProvider</b> (Cube, Infoset, etc)...or they can be used in queries
on different infoprovider...
Please suggest...Thanks in Advance.
Regards
AnilHi Bhanu,
Needed some help defining the Precalculated Value Set as I wasnt succesful....
Please suggest answers if possible for the questions below
1) Can I use Filter Criteria for restricting the value set for the characteristic when I Define a Query on an ODS. When i tried this it gave me errors as below ..
"System error in program CL_RSR_REQUEST and form EXECUTE_VTABLE:COB_PRO_GET_ALWAYS.... Error when filling value set DELIVERY..
Job cancelled after system exception ERROR_MESSAGE"
2) Can I create a create a Value Set predefined on an Infoset - Not Succesful as Infoset have names such as "InfosetName_F000232" and cannot find the characteristic in Paramter Tab for Value Set in Reprting Agent.
3) How does the precalculated value Set variable help if I am not using any Filtering Criteria and is storing the List of all values for the Variable from the ODS which consists of 20 millio records.
Thanks for your help.
Kind Regards
Anil -
HI,
Could you pls. tell me the use of the subquery in different clauses; such as;
1. when to use the subquery in the FROM clause ?
2. when to use the subquery in the WHERE clause ?
3. when to use the select statement within the select statement; such as, select last_name, (select employee_id.......) ?
I am aware of that in real life the usage of the subquery depends on the requirements whcih is encountered.
If you have any document (pdf/word doc) / source where the the usage of the subquery is broadly elaborated with example (preferaby based on EMPLOYEES and DEPARTMENTS tables), pls. let me know. It will help me a lot.
Warm regards,Hi,
Tapash wrote:
HI,
Could you pls. tell me the use of the subquery in different clauses; such as;
1. when to use the subquery in the FROM clause ? That's called an in-line view.
Use it when you want to treat the result set of a query as if it were a table.
In Oracle 9 (and up) you can also us the WITH clause for this purpose.
2. when to use the subquery in the WHERE clause ? There are two specail types of qub-queries, EXISTS- and IN sub-queries, that return boolean values.
Use them when they help you get the results you need.
They're not restricted to WHERE clauses: you can use EXISTS and IN sub-queries in CASE statements in other clauses, too.
3. when to use the select statement within the select statement; such as, select last_name, (select employee_id.......) ? That's called a scalar sub-query.
Use it when you want to treat the result set as if it were a single value.
Scalar sub-queries are not restricted to the SELECT clause: you can use them in other clauses, too.
I am aware of that in real life the usage of the subquery depends on the requirements whcih is encountered. Exactly. All of these are tools. Not all tools are appropriate for all jobs. -
HI,
how ro write nested multiple row ( row should consist range of values )sub query between tables if they dont have any common column.
Based on this weight range I have to group the other columns.
For eg:
My table should contain
weight-range:
1-> 2
2->3
3->4
etcPlease repost your question adding clarity and an example so we can understand what you are asking. Also include your full version number.
SELECT * FROM v$version; -
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 -
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
Maybe you are looking for
-
I have sent an e-mail to Rapidshare. They have tested the button and it works fine. Rapidshare recommended to try another web browser. I have tried Internet Explorer and the button works fine. It's probably a Firefox 12 problem. In former Firefox ver
-
Trying to do an Insert but ADF framework is tryng to do Update
I have JSF create screen where the user wants to either fill out all the fields on the page and then save them, or select a record from a select list and have all the fields from the selected record copied into the create screens fields. When the use
-
Unselecting Data List in custom component
Hi, I am trying to make a dropdown menu. I've followed instructions here: http://cookbooks.adobe.com/post_Creating_a_custom_combobox_component_using_Flash_C-17234.h tml and it works well but there is a problem. Here's what I did. Created a custom co
-
I have a G530 4446-36U running Windows 7 Ultimate (originally running Vista), and my wireless seems to have gone kaput. Originally my wireless kept randomly turning off, but now whenever I connect to a network, it says that the computer is communica
-
Lightening to 30 pin Adaptor issues
Recently bought a genuine lightening to 30 pin Adaptor from JR ,but whenever i use the 30 pin cable with this adaptor , the IP5 behaves erraticly. Many time the touchscreen stops responding or apps start to launch on its own. There is not particular