Using Global Temporary Table in Subquery gives NULL - oracle

I am using following query.
SELECT SYSDATE,(SELECT P_PRICE_OPEN FROM GTT_ADJ_PRICE_TABLE WHERE FSYM_ID='P8R3C2-R' AND P_DATE='22-OCT-18' AND P_VOLUME<>0 AND ROWNUM=1) FROM DUAL;
GTT_ADJ_PRICE_TABLE is global temporary table loaded with values when i have executed a function related to it. This GTT preserves rows after commit. This query gives me correct results.
But, If i run the query
SELECT WEEK_END, WEEK_START,
(SELECT P_PRICE_OPEN FROM GTT_ADJ_PRICE_TABLE WHERE P_DATE=WEEK_START) AS WEEKS_OPEN_PRICE,
(SELECT MAX(P_PRICE_HIGH) FROM GTT_ADJ_PRICE_TABLE WHERE FSYM_ID=FID AND P_DATE<=WEEK_END
AND P_DATE>=WEEK_START AND P_VOLUME<>0) AS WEEKLY_HIGH,
(SELECT MIN(P_PRICE_LOW) FROM GTT_ADJ_PRICE_TABLE WHERE FSYM_ID=FID AND P_DATE<=WEEK_END
AND P_DATE>=WEEK_START AND P_VOLUME<>0) AS WEEKLY_LOW,
(SELECT SUM(P_VOLUME) FROM GTT_ADJ_PRICE_TABLE WHERE FSYM_ID=FID AND P_DATE<=WEEK_END
AND P_DATE>=WEEK_START AND P_VOLUME<>0) AS WEEKLY_VOLUME,
P_PRICE
FROM (
SELECT ROWNUM,FID,WEEK_END,P_VOLUME,P_PRICE,
(SELECT P_DATE FROM FP_V2_FP_BASIC_PRICES WHERE FSYM_ID=FID AND P_DATE>=TRUNC(WEEK_END, 'IW') AND P_VOLUME<>0 AND ROWNUM=1) AS WEEK_START
FROM (
SELECT
ROWNUM,FSYM_ID AS FID, WEEK_END,P_VOLUME, P_PRICE,P_PRICE_OPEN,P_PRICE_HIGH,P_PRICE_LOW
FROM (
SELECT ROWNUM,FSYM_ID,P_DATE AS WEEK_END, P_PRICE,P_VOLUME, P_PRICE_OPEN,P_PRICE_HIGH,P_PRICE_LOW,
CASE
WHEN (TO_CHAR(P_DATE,'D') >= AVG(TO_CHAR(P_DATE,'D')) OVER (order by P_DATE DESC rows between 1 preceding and current row) and ROWNUM>=1) or TO_CHAR(P_DATE,'D')=6
THEN 1
ELSE 0
END AS WEEKFLAG
FROM(
SELECT * FROM TABLE (ADJUSTED_PRICE('P8R3C2-R')) WHERE P_VOLUME<>0
)
)WHERE WEEKFLAG=1
)
);
It gives me NULL in WEEKS_OPEN_PRICE,WEEKLY_HIGH,WEEKLY_LOW,WEEKLY_VOLUME.
Please help me to resolve the issue. Thanks in anticipation.

Try with WITH clause. I hope a below query works. I don't have possibility to check.
WITH adjustedPrice AS (
SELECT *
FROM TABLE(adjusted_price('P8R3C2-R'))
WHERE p_volume <> 0
AND TO_CHAR(p_date, 'DY') NOT IN ('SAT', 'SUN')
)
SELECT ap.week,
ap.week_start,
ap.week_end,
ap.weeks_high_price,
ap.weeks_low_price,
ap.weekly_volume,
ws.p_price_open AS weeks_open_price,
we.p_price AS weeks_close_price
FROM (
SELECT TRUNC(p_date, 'IW') AS week,
TRUNC(MIN(p_date)) AS week_start,
TRUNC(MAX(p_date)) AS week_end,
MAX(p_price_high) AS weeks_high_price,
MIN(p_price_low) AS weeks_low_price,
SUM(p_volume) AS weekly_volume
FROM adjustedPrice
GROUP BY TRUNC(p_date, 'IW')
) ap
INNER JOIN adjustedPrice ws ON ws.p_date = ap.week_start
INNER JOIN adjustedPrice we ON we.p_date = ap.week_end
ORDER BY week DESC;

Wanted to post as a comment. But it wont fit there thats why writing it as an answer.
I tried this code to get the week start, end , weeks high price, weeks low price, weekly volume.
select
trunc("P_DATE", 'IW') as week,
min(trunc("P_DATE")) as week_start,
max(trunc("P_DATE")) as week_end,
MAX(P_PRICE_HIGH) AS WEEKS_HIGH_PRICE,
MIN(P_PRICE_LOW) AS WEEKS_LOW_PRICE,
SUM(P_VOLUME) AS WEEKLY_VOLUME
from TABLE
(ADJUSTED_PRICE('P8R3C2-R'))
WHERE
P_VOLUME<>0 AND to_char("P_DATE", 'DY') not in ('SAT','SUN')
group by
trunc("P_DATE", 'IW')
ORDER BY
trunc("P_DATE", 'IW') DESC;
That gave me results in hardly 2-4 seconds. But i want to get the weeks open price where date will be equal to WEEK_START and weeks closing price where date will be equal to WEEK_END.
I tried following approach for the same. But its taking too much time (like 300+ seconds).
SELECT
WEEK,WEEK_START, WEEK_END, WEEKS_HIGH_PRICE,WEEKS_LOW_PRICE,WEEKLY_VOLUME,
(SELECT P_PRICE_OPEN FROM TABLE (ADJUSTED_PRICE('P8R3C2-R')) WHERE P_VOLUME<>0 AND P_DATE=WEEK_START) AS WEEKS_OPEN_PRICE,
(SELECT P_PRICE FROM TABLE (ADJUSTED_PRICE('P8R3C2-R')) WHERE P_VOLUME<>0 AND P_DATE=WEEK_END) AS WEEKS_CLOSE_PRICE
FROM
(
select
trunc("P_DATE", 'IW') as week,
min(trunc("P_DATE")) as week_start,
max(trunc("P_DATE")) as week_end,
MAX(P_PRICE_HIGH) AS WEEKS_HIGH_PRICE,
MIN(P_PRICE_LOW) AS WEEKS_LOW_PRICE,
SUM(P_VOLUME) AS WEEKLY_VOLUME
from TABLE
(ADJUSTED_PRICE('P8R3C2-R'))
WHERE
P_VOLUME<>0 AND to_char("P_DATE", 'DY') not in ('SAT','SUN')
group by
trunc("P_DATE", 'IW')
ORDER BY
trunc("P_DATE", 'IW') DESC
);
If anybody can help me to improve the output time is most welcome.

Related

First_Day/Last_Day Query

Could you please help me to correct the script as below:
set LastDay=SELECT LAST_DAY(SYSDATE) FROM dual;
set FirstDay=Select trunc((sysdate),'month') as First_day_of_month from dual;
SELECT count(*) FROM tab1 g , h.ab1 LEFT JOIN tab2 h ON g.bba = h.bba
WHERE 1 = 1
AND g.DATE_ BETWEEN TO_DATE('FirstDay', 'YYYYMMDD') AND TO_DATE('LastDay', 'YYYYMMDD');
In Oracle, a DATE ALWAYS has year, month, day, hour, minute and second components. Using LAST_DAY(SYSDATE) only sets the year-month-day component of a date and does not modify the time component so if you filter from the start of the month to LAST_DAY(SYSDATE) then you will exclude any values from the last day of the month with a time component between the current time and 23:59:59.
What you want is to use:
SELECT count(*)
FROM tab1 g
CROSS JOIN h.ab1 -- your query is confusing around the joins
-- and may need fixing
LEFT JOIN tab2 h
ON g.bba = h.bba
WHERE g.DATE_ >= TRUNC(SYSDATE, 'MM')
AND g.DATE_ < ADD_MONTHS(TRUNC(SYSDATE, 'MM'), 1);
That's just
select count(*)
from tab1 g left join tab2 h on g.bba = h.bba
and g.date_ between trunc(sysdate, 'month') and last_day(sysdate);
Isn't it?

Adding hours variable to date variable in Oracle

OK all-This may be simple but I can't see to find an answer via Google.
So I have a date value ('01/01/2020') and in another column I have a variable of hours (let's say 5) that needs to be added. SO I would have 01-JAN-20 05:00:00 in the end.
Any suggestions helpful. Thanks-
with t1 as (select TO_DATE('01/01/2020','DD/MM/YYYY') as DT, '5' as HR FROM DUAL)
select t1.* , ???? from t1;
You may simply add the correct fraction of a day, given the hour value:
WITH t1 AS (
SELECT TO_DATE('01/01/2020', 'DD/MM/YYYY') AS DT, '5' AS HR
FROM DUAL
),
t2 AS (
SELECT DT, DT + TO_NUMBER(HR) / 24 AS NEW_DT
FROM t1
)
SELECT
TO_CHAR(DT, 'DD-MM-YYYY HH24:MI:SS') AS DT,
TO_CHAR(NEW_DT, 'DD-MM-YYYY HH24:MI:SS') AS NEW_DT
FROM t2;
Demo
You can also use interval clause as follows:
with t1 as (select TO_DATE('01/01/2020','DD/MM/YYYY') as DT, '5' as HR FROM DUAL)
select t1.* ,
t1.dt + hr * interval '1' hour as new_dt -- this is solution
from t1;

How to convert this code from oracle to redshift?

I am trying to implement the same in redshift and i am finding it little difficult to do that. Since redshift is in top of postgresql engine, if any one can do it in postgresql it would be really helpfull. Basically the code gets the count for previous two month at column level. If there is no count for exact previous month then it gives 0.
This is my code:
with abc(dateval,cnt) as(
select 201908, 100 from dual union
select 201907, 200 from dual union
select 201906, 300 from dual union
select 201904, 600 from dual)
select dateval, cnt,
last_value(cnt) over (order by dateval
range between interval '1' month preceding
and interval '1' month preceding ) m1,
last_value(cnt) over (order by dateval
range between interval '2' month preceding
and interval '2' month preceding ) m2
from (select to_date(dateval, 'yyyymm') dateval, cnt from abc)
I get error in over by clause. I tried to give cast('1 month' as interval) but still its failing. Can someone please help me with this windows function.
expected output:
Regards
This is how I would do it. In Redshift there's no easy way to generate sequences, do I select row_number() from an arbitrary table to create a sequence:
with abc(dateval,cnt) as(
select 201908, 100 union
select 201907, 200 union
select 201906, 300 union
select 201904, 600),
cal(date) as (
select
add_months(
'20190101'::date,
row_number() over () - 1
) as date
from <an arbitrary table to generate a sequence of rows> limit 10
),
with_lag as (
select
dateval,
cnt,
lag(cnt, 1) over (order by date) as m1,
lag(cnt, 2) over (order by date) as m2
from abc right join cal on to_date(dateval, 'YYYYMM') = date
)
select * from with_lag
where dateval is not null
order by dateval

I am getting 2 different row counts from the same statement executed in different locations

I have a statement that collapses date ranges and I am getting the proper collapsed version when executing the SQL by iteself and when inserting it into a nested table in a procedure I am getting a row that should have been collapsed into the other row.
SELECT client_pk,
plan_id,
grp,
MIN(start_dt) start_dt,
MAX(end_dt) end_dt
FROM (
SELECT client_pk
plan_id,
start_dt,
end_dt,
MAX(grp) OVER (PARTITION BY plan_id ORDER BY start_dt ASC) grp
FROM (
SELECT mp.client_pk,
mp.plan_id,
CASE
WHEN (LAG(mp.end_dt) OVER (PARTITION BY mp.plan_id ORDER BY mp.start_dt ASC)) BETWEEN mp.start_dt-1 AND
NVL(mp.end_dt,to_date('12/31/9999','MM/DD/YYYY'))
THEN NULL
ELSE ROWNUM
END grp,
mp.start_dt,
NVL(mp.end_dt,to_date('12/31/9999','MM/DD/YYYY')) end_dt
FROM client_plan mp
)
)
GROUP BY grp, plan_id, client_pk
So I have an initial result set from the inner most query to give a ROWNUM of:
client_pk PLAN_ID GRP start_dt end_dt
8752 25171 3 1/1/2016 3/31/2016
8752 25171 1 2/1/2016 1/31/2016
and by the end, it is collapsed appropriately when execute as a stand alone query
client_pk PLAN_ID GRP start_dt end_dt
8752 25171 3 1/1/2016 3/31/2016
But when run though a procedure that dumps these records into a nested table that will then eventually be inserted into the DB, both rows are still returned.
SELECT plan_spans_obj(client_pk, plan_id, start_dt, end_dt)
BULK COLLECT INTO plan_spans_ins_tbl
FROM (
SELECT client_pk,
plan_id,
start_dt,
end_dt
FROM ( SELECT client_pk,
plan_id,
grp,
MIN(start_dt) start_dt,
MAX(end_dt) end_dt
FROM (
SELECT client_pk
plan_id,
start_dt,
end_dt,
MAX(grp) OVER (PARTITION BY plan_id ORDER BY start_dt ASC) grp
FROM (
SELECT mp.client_pk,
mp.plan_id,
CASE
WHEN (LAG(mp.end_dt) OVER (PARTITION BY mp.plan_id ORDER BY mp.start_dt ASC)) BETWEEN mp.start_dt-1 AND
NVL(mp.end_dt,to_date('12/31/9999','MM/DD/YYYY'))
THEN NULL
ELSE ROWNUM
END grp,
mp.start_dt,
NVL(mp.end_dt,to_date('12/31/9999','MM/DD/YYYY')) end_dt
FROM client_plan mp
)
)
GROUP BY grp, plan_id, client_pk
)
);
So how am I getting 2 different results from the same query, just executed differently, is it an order of operation different depending on where it is executed.
Also, the extra record is essentially a negative time span, end date being before the start date but this is handled in the query.
The answer was that I didn't initialize the collection. Can't believe it was something like that but apparently so. Seems to be working now.

self join with max value

I am have a table with 500k transactions. I want to fetch the last balance for a particular date. So I have have returned a query like below.
SELECT curr_balance
FROM transaction_details
WHERE acct_num = '10'
AND is_deleted = 'N'
AND ( value_date, srl_num ) IN(
SELECT MAX( value_date ), MAX( srl_num )
FROM transaction_details
WHERE TO_DATE( value_date, 'dd/mm/yyyy' )
<= TO_DATE( ADD_MONTHS( '05-APR-2012', 1 ), 'dd/mm/yyyy' )
AND acct_num = '10'
AND is_deleted = 'N'
AND ver_status = 'Y' )
AND ver_status = 'Y'
This has to be executed for incrementing of 12 months to find the last balance for each particular month. But this query is having more cpu cost, 12 times it is taking huge time. How to remodify the above query to get the results in faster way. Whether this can be broken into two part in PL/SQL to achieve the performance. ?
Try:
select * from(
SELECT value_date, srl_num, curr_balance
FROM transaction_details
WHERE acct_num = '10'
AND is_deleted = 'N'
AND ver_status = 'Y'
row_number() over (partition by trunc(value_date - interval '5' day,'MM')
order by srl_num desc
) as rnk
)
where rnk = 1;
You'll get a report with the ballance on last srl_num on each month in your table.
The benefit is that your approach scans the table 24 times for 12 months report and my approach scans the table once.
The analytic function gets the rank of record in current month(partition by clause) ordering the rows in the month after srl_num.
You don't have to query your table twice. Try using analytic functions
SELECT t.curr_balance
-- , any other column you want as long it is in the subselect.
FROM (
SELECT
trans.curr_balance
, trans.value_date
-- any other column you want
, trans.srl_num
, MAX(trans.srl_num) OVER(PARTITION BY trans.value_date, trans.srl_num) max_srl_num
, MAX(trans.value_date) OVER(PARTITION BY trans.value_date, trans.srl_num) max_date
FROM transaction_details trans
WHERE TO_DATE( value_date, 'dd/mm/yyyy' ) <= TO_DATE( ADD_MONTHS( '01-APR-2012', 1 ), 'dd/mm/yyyy' )
AND acct_num = '10'
AND is_deleted = 'N'
AND ver_status = 'Y'
) t
WHERE t.max_date = t.value_date
AND t.max_srl_num = t.srl_num
A couple of thoughts.
Why do you have TO_DATE( value_date...? Isn't your data type DATE? this might be breaking your index if you have one in that column.
Note that (this is a wild guess) if your srl_num is not the highest for the latest date, you will have incorrect results and might not return any rows.

Resources