Lag function
Oracle version: 11.0.2.0.2.0
Dear all
I have a question where I am using tables Tab1 and Tab2
Struncture of tab1 is
Store_no NUMBER,
Sell_date DATE
Sell quantity number,
number of item_no
to tab2
Number of Item_no
date date1,
number of item_price
I need know the total price of the article sold for 2 days (current as previous)
Select the store, sell_date, item_no, sell_qty * item_price, lag (sell_qty * item_price, 1) on the partition by (store_no, item_no order of sell_date)
of tab1, tab2
where tab1.item_no = tab2.item_no
and sell_date = date1
Question1) tables have millions of lines... The lag function is causing the query to run for hours...
Could you please suggest if we capture these sorts of queries where Lag/lead are used.
Your query does not much sense. Analytical functions are applied to already recovered lines, and since you have sell_date = date1, all you get is one day sales. All you need is:
Select the store
Max (sell_date),
tab1.item_no,
sum (case sell_date when date1 then sell_qty * end item_price) day_sales_amount,.
sum (case sell_date when date1 - sell_qty then 1 * item_price end) prev_day_sales_amount
of tab1.
tab2
where tab1.item_no = tab2.item_no
and sell_date in the fields (date1, date1 - 1).
Store group,
tab1.item_no;
SY.
Tags: Database
Similar Questions
-
Hi all
I want to understand the inner workings of the Lag function in Oracle, which could help to solve my problem.
I have the table as the structure below.
P_ID ENTRY_TIMESTAMP SIZE C_ID 15287 1 NOVEMBER 15 05.45.00 PM 30 92 15295 06.00.00 PM 1ST NOVEMBER 15 15 92 15306 06.00.00 PM 1ST NOVEMBER 15 1 92 Now, when I write a query as below:
Select the size, CURR_TIMESTAMP TO_TIMESTAMP (TO_CHAR (ENTRY_TIMESTAMP, 'YYYYMMDDHH24MI'), 'YYYYMMDDHH24MI'),
TO_TIMESTAMP (TO_CHAR (LAG (ENTRY_TIMESTAMP) OVER (PARTITION BY ORDER BY ENTRY_TIMESTAMP ASC C_ID), 'YYYYMMDDHH24MI'), 'YYYYMMDDHH24MI') LAG_TIMESTAMP
OF Entry_log
where ENTRY_TIMESTAMP BETWEEN to_date (1 November 15 18.00.00','DD-MON-YY HH24.MI.) SS') AND to_date (1 November 15 18.00.00','DD-MON-YY HH24.MI.) SS')
Query will lead to give Lag_timestamp as 06.00.00 PM for size = 1 but will be NULL for size = 15.
Why is that Oracle will never lag_timestamp = 06.00.00 PM for size = 15.
Could someone please explain this behavior.
I'm using Oracle 11 g.
Thank you
I had a small mistake in the above query. now, I fixed it
-
LAG function alternative queries
Dear all,
WITH t AS
(SELECT 1 AS num, "test1" AS status
OF THE DOUBLE
UNION ALL
SELECT 2 AS num, "test2" LIKE status
OF THE DOUBLE
UNION ALL
SELECT 3 AS num, "test3" LIKE status
OF THE DOUBLE
UNION ALL
SELECT the 4 ACEs num, "test4" LIKE status
OF THE DOUBLE
UNION ALL
SELECT 5 AS num, "test5" LIKE status
THE DOUBLE)
SELECT the State, LAG (status 1) OVER (ORDER BY num) AS previous_status
T
Please help me to write search above without LAG function like oracle forms10g unsupported feature LAG.
Hello, you can join the table itself for the results. This will work only if you have a number in ascending order.
WITH t AS
(SELECT 1 AS num, "test1" AS status
OF THE DOUBLE
UNION ALL
SELECT 2 AS num, "test2" LIKE status
OF THE DOUBLE
UNION ALL
SELECT 3 AS num, "test3" LIKE status
OF THE DOUBLE
UNION ALL
SELECT the 4 ACEs num, "test4" LIKE status
OF THE DOUBLE
UNION ALL
SELECT 5 AS num, "test5" LIKE status
THE DOUBLE)
T1.status, t2.status SELECT previous_status
T t1, t t2
where t2.num (+) = t1.num - 1
order of t1.status
Best regards, Andrei
-
LAG function to get the value of the measurement for parent
Hello
I'm interested if there is no function in OLAP DML, which is similar to the function of TROLLING. LAG function returns the measured value for the previous dimension member (or a few members of the back dimension). I would like to know if this function exists which does not return a meaningless measurement for the dimension member value, but the measured value for the parent of the live dimension member.
Thanks in advance
Peter_parentrel relationship identifies the parent of each Member of the dimension of a hierarchy. use:
the time - dimension
time_parentrel - Member parent expression
time_parentrel (time_hierlist 'CALENDAR') - expression for parent along the CALENDAR hierarchySales - measure
Sales (Time time_parentrel) - expression returning sales for the parent of the current Member along the existing hierarchy.
sales (time time_parentrel (time_hierlist 'EXERCISE'))-expression returning the sales for the parent of the current Member along the FISCAL hierarchy.You can search the user's Guide the OLAP DML for many examples of the use of the OLAP DML commands/functions/objects in expressions.
All of these objects are automatically created/maintained while retaining the dimension from the front end (MN).For example:
(11g) OLAP DML users guide notions-> about-> OLAP DML objects given OLAP DML-> objects that support the use of hierarchical Dimensions section. -
Oracle 11.2.0.1.0 SE - one on OL 5.6 x 86-64
Still faced with a LAG.
Given a table like this
Table is added every day withcreate table emp_hist ( sample_date date, lname varchar2(10), dept varchar2(10), sal number ) ;
Of course, most of the time, most of the employees will have no change from the previous. What I'm trying to do is filtering all the records of 'no change' and get off at only changes... amount of change and when it appearedinsert into emp_hist (select sysdate, lname, dept, sal from emp) ;
Maybe this:
or (better)dept lname sample_date sal ---- ----- ----------- ------- 10 smith 1-Aug-2012 10000 2-Aug-2012 20000 10 jones 5-Aug-2012 50000 6-Aug-2012 60000 20 snuffy 4-Aug-2012 30000 5-Aug-2012 40000
Wish I could show what I tried so far, but I'm so stuck, I can't even that.dept lname change_date prev_sal curr_sal ---- ----- ----------- ------- -------- 10 smith 2-Aug-2012 10000 20000 10 jones 6-Aug-2012 50000 60000 20 snuffy 5-Aug-2012 30000 40000
Hello
Looks like:
WITH got_prev_sal AS ( SELECT dept , lname , sample_date AS change_date , LAG (sal) OVER ( PARTITION BY lname ORDER BY sample_date ) AS prev_sal , sal AS curr_sal FROM emp_hist ) SELECT * FROM got_prev_sal WHERE prev_sal != curr_sal ORDER BY lname , change_date ;
In any application data (or subquery), analytical functions are calculated after the clause WHERE this request has been applied. If you need to use the results of an analytic function in a WHERE clause, calculate the analytical function in a subquery (such as got_prev_sal, above). You can then use the value returned in the WHERE clause (or elsewhere) in the main query.
I hope that answers your question.
If not, post a small example data (instructions INSERT, to go with the CREATE TABLE statement, you have already published) and also publish outcomes from these data.
Point where the above query is to produce erroneous results, and explain, using specific examples, how you get the right results in these places.
See the FAQ forum {message identifier: = 9360002}Published by: Frank Kulash, August 7, 2012 16:29
-
get my head wrapped around the LAG function
Oracle 11.2.0.4 Std Ed
drop table change_hist;
create table change_hist (file_name varchar2 (30),)
date of sample_date,
number of blocks
);
insert into change_hist values (to_date('2015-07-01','yyyy-mm-dd'), 'file1', 5);
insert into change_hist values (to_date('2015-07-02','yyyy-mm-dd'), 'file1', 5);
insert into change_hist values (to_date('2015-07-03','yyyy-mm-dd'), 'file1', 6);
insert into change_hist values (to_date('2015-07-04','yyyy-mm-dd'), 'file1', 6);
insert into change_hist values (to_date('2015-07-05','yyyy-mm-dd'), 'file1', 6);
insert into change_hist values (to_date('2015-07-01','yyyy-mm-dd'), 'file2', 5);
insert into change_hist values (to_date('2015-07-02','yyyy-mm-dd'), 'file2', 5);
insert into change_hist values (to_date('2015-07-03','yyyy-mm-dd'), 'file2', 5);
insert into change_hist values (to_date('2015-07-04','yyyy-mm-dd'), 'file2', 5);
insert into change_hist values (to_date('2015-07-05','yyyy-mm-dd'), 'file2', 5);
insert into change_hist values ('file3', to_date('2015-07-01','yyyy-mm-dd'), 5);
insert into change_hist values ('file3', to_date('2015-07-02','yyyy-mm-dd'), 6);
insert into change_hist values ('file3', to_date('2015-07-03','yyyy-mm-dd'), 6);
insert into change_hist values ('file3', to_date('2015-07-04','yyyy-mm-dd'), 6);
insert into change_hist values ('file3', to_date('2015-07-05','yyyy-mm-dd'), 6);
Desired result
file_name sample_date prev_value curr_value
File1 2015-07-03 5 6
File2 2015-07-02 5 6
My first attempt...
SQL > select file_name,.
2 sample_date,
3 lag (blocks, 1) (order sample_date) as prev_blocks
4 change_hist;
FILE_NAME SAMPLE_DA PREV_BLOCKS
------------------------------ --------- -----------
July 1, 15 file1
July 1, 15 5 file3
July 1, 15 5 File2
File2 2 July 15 5
File1 2 July 15 5
file3 2 July 15 5
File1 July 3, 15 6
File2 July 3, 15 6
file3 July 3, 15 5
File1 4 July 15 6
file3 4 July 15 6
FILE_NAME SAMPLE_DA PREV_BLOCKS
------------------------------ --------- -----------
File2 4 July 15 6
File2 July 5 15 5
File1 July 5 15 5
file3 5 July 15 6
15 selected lines.
SQL >
SQL > spo off
1 select * from (select file_name, sample_date, lag(blocks) over (partition by file_name order by sample_date) prev, blocks 2 from change_hist) 3* where prev != blocks SQL> / FILE_NAME SAMPLE_DA PREV BLOCKS ------------------------------ --------- ---------- ---------- file1 03-JUL-15 5 6 file3 02-JUL-15 5 6
You know... you need to partition the file name
Edit: in the interest of beat some people with a force equal regardless of their status, you didn't really know we tell how to achieve these results, so I could refer to the FAQ on how to ask a question
-
Oracle 10.2.0.4 SE - One on OL 5 x 86-64
Trying to write reports on statspack tables. In view of this query
Works perfectly. But I would like to delete the ' where... w1.event = 'db file sequential read' and get a report on all events. Of course, simply commenting on this condition means that the first occurrence of an event is "shifted" against the last occurrence of the previous event. Can not find a way to get the logic that do break and start the 'delay' all over again.select -- s1.ucomment w1.event , s1.snap_id , to_char(s1.snap_time,'dd-Mon-yyyy hh24:mi:ss') snap_time , lag(w1.total_waits) over (order by s1.snap_id) prev_val, w1.total_waits - lag(w1.total_waits) over (order by s1.snap_id) delta_val , lag(w1.time_waited_micro) over (order by s1.snap_id) prev_val, w1.time_waited_micro - lag(w1.time_waited_micro) over (order by s1.snap_id) delta_val from stats$snapshot s1 , stats$system_event w1 where s1.snap_id = w1.snap_id and w1.event = 'db file sequential read' order by w1.event , s1.snap_id ; EVENT SNAP_ID SNAP_TIME PREV_VAL DELTA_VAL PREV_VAL DELTA_VAL ---------------------------------------------------------------- ---------- -------------------- ---------- ---------- ---------- ---------- db file sequential read 1 25-Apr-2013 11:00:51 db file sequential read 2 25-Apr-2013 12:00:51 959235 39179 949588625 29088092 db file sequential read 3 25-Apr-2013 13:00:51 998414 29632 978676717 24938574 db file sequential read 4 25-Apr-2013 14:00:52 1028046 21547 1003615291 23101379 4 rows selected.
You use lag (...) over (partition by the order of the events of snap_id), i.e. "partition by the event" will do lag a ' star on "for each different event
-
Row1-row2(without lead and lag function)
Hello
I wanted less row1 - row2 can I could use at least conditions he same for 1000 lines and should not use the features of lead and lag
Thank youIt if self explaining IMHO
with data as ( select 9 r from dual union all select 7 from dual union all select 6 from dual union all select 3 from dual ) , rdata as ( select r, row_number() over (order by r desc) rn from data ) select d1.r - nvl(d2.r, '0') res from rdata d1, rdata d2 where d1.rn +1 =d2.rn(+) RES 2 1 3 3
Concerning
-
Using the LAG function to find a previous record
Hey,.
I tried searching the forum for this, but I didn't actually even know what to look for, so I create a new thread.
The SQL below displays a list of prices:
The challenge is to produce this output:WITH T AS ( SELECT 1 AS ID, 'PERM' AS TYPE, 100 AS PRICE, SYSDATE + 1 AS START_DATE FROM DUAL UNION SELECT 3 AS ID, 'TEMP' AS TYPE, 90 AS PRICE, SYSDATE + 2 AS START_DATE FROM DUAL UNION SELECT 7 AS ID, 'TEMP' AS TYPE, 80 AS PRICE, SYSDATE + 3 AS START_DATE FROM DUAL UNION SELECT 8 AS ID, 'PERM' AS TYPE, 75 AS PRICE, SYSDATE + 4 AS START_DATE FROM DUAL UNION SELECT 16 AS ID, 'TEMP' AS TYPE, 70 AS PRICE, SYSDATE + 5 AS START_DATE FROM DUAL UNION SELECT 20 AS ID, 'TEMP' AS TYPE, 60 AS PRICE, SYSDATE + 6 AS START_DATE FROM DUAL UNION SELECT 34 AS ID, 'TEMP' AS TYPE, 50 AS PRICE, SYSDATE + 7 AS START_DATE FROM DUAL ) SELECT T.ID , T.TYPE , T.PRICE , TRUNC (T.START_DATE) AS START_DATE , CASE WHEN T.TYPE = 'PERM' THEN T.ID ELSE LAG (T.ID, 1, NULL) OVER (PARTITION BY NULL ORDER BY T.ID) END AS BASE_ID FROM T ORDER BY T.START_DATE
What I want to achieve is to bring a column with the ID of the most recent prices of TEMP PERM price.ID TYPE PRICE BASE_ID 1 PERM 100 1 3 TEMP 90 1 7 TEMP 80 1 8 PERM 75 8 16 TEMP 70 8 20 TEMP 60 8 34 TEMP 50 8
and it's own ID of prices of PERM.
My attempt using LAG to browse the set of records, but it uses 1 statically. If there was a way to arrive at a number
for each TEMP price say to what extent is the most recent Perm, then I could use that number instead of 1.
Something like:
Any help will be greatly appreciated.ID TYPE PRICE DISTANCE_FROM_PREV_PERM 1 PERM 100 0 3 TEMP 90 1 7 TEMP 80 2 8 PERM 75 0 16 TEMP 70 1 20 TEMP 60 2 34 TEMP 50 3
Thank you.Maybe
select id,type,price, last_value(base_id) ignore nulls over (order by the_row) base_id /* last_value(base_id ignore nulls) over (order by the_row) base_id -- old way */ from (select id,type,price,start_date, case type when 'PERM' then id end base_id, row_number() over (order by start_date) the_row from t )
Concerning
Etbin
-
I think I need a LEAD/LAG function?
Hello
Oracle 10.2.0.4
I have a table that contains an atrribute used over time. Number of lines does not change the value and is there only to maintain integrity between the lines of other tables.
CREATE THE EMP_ATTR TABLE (EMPID VARCHAR2 (8) NOT NULL, ASOFDATE DATE NOT NULL, ATTR VARCHAR2 (13));
Values inserted INTO the EMP_ATTR ("'001', January 1, 2010 ', ' XX');
INSERT INTO EMP_ATTR VALUES ('001', FEBRUARY 2, 2011 "," YY");
INSERT INTO EMP_ATTR VALUES ('001', MARCH 4, 2011 "," YY");
INSERT INTO EMP_ATTR VALUES ('002', JANUARY 1, 2010 "," TT");
INSERT INTO EMP_ATTR VALUES (' '002', 1ST FEBRUARY 2010 TT ', ' ');
INSERT INTO EMP_ATTR VALUES (' '002', 1 DECEMBER 2013 ', ' TT');
INSERT INTO EMP_ATTR VALUES (' '003', JANUARY 1, 2010 ', ' EW');
INSERT INTO EMP_ATTR VALUES (' '003', MARCH 2, 2010 ', ' RT');
INSERT INTO EMP_ATTR VALUES (' '003', 1 NOVEMBER 2013 EW ', ' ');
INSERT INTO EMP_ATTR VALUES (' '003', 1 DECEMBER 2013 EW ', ' ');
What I have to do is to analyze the table, and for each return line when the person assigned this attribute, without going through another attribute assigned in the meantime
So I need something that will return
EMPID, ATTR, ASOFDATE, FIRST_ASOFDATE
001, XX, JANUARY 1, 2010, JANUARY 1, 2010
001, YY, FEBRUARY 2, 2011, FEBRUARY 2, 2011
001, YY, March 4, 2011, February 2, 2011 <-as this was awarded in February and the line of March has not changed the attribute
002, TT, JANUARY 1, 2010, JANUARY 1, 2010
002, TT, FEBRUARY 1, 2010, JANUARY 1, 2010
002, TT, DECEMBER 1, 2013, JANUARY 1, 2010
003, EW, JANUARY 1, 2010, JANUARY 1, 2010
003, RT, MARCH 2, 2010, MARCH 2, 2010
003, EW, November 1, 2013, November 1, 2013 <-EW was previously assigned in 2010, but they have a RT line between Mar-2010 so it's seen as a reboot
003, EW, December 1, 2013, November 1, 2013 <-there was no intermediate attribute inherit so assignment NOV forward
Can be
SQL > select empid, asofdate, attr, asofdate_first
25 years of emp_attr
model 26
27 partition by (empid)
size 28 per (row_number() over (partition by asofdate order empid) rno)
29 measures (asofdate, attr, sysdate asofdate_first, ' ' attr_prev)
30 rules
(31)
32 attr_prev [any] = attr [cv () - 1],
33 asofdate_first [any] = decode (attr_prev [cv ()], attr [cv ()], [cv () - 1] asofdate_first, asofdate [cv ()])
34)
35 order by empid, asofdate;EMP ASOFDATE TO ASOFDATE_
--- --------- -- ---------
001-1 JANUARY 10 XX 1 JANUARY 10
001 2 FEBRUARY 11 AA 2 FEBRUARY 11
001 4 MARCH 11 AA 2 FEBRUARY 11
002 1 JANUARY 10 TT 1 JANUARY 10
002 1 FEBRUARY 10 TT 1 JANUARY 10
002 1 DECEMBER 13 TT 1 JANUARY 10
003 1 JANUARY 10 EW 1 JANUARY 10
003 2 MARCH 10 RT 2 MARCH 10
1ST NOVEMBER 13 003 EW 1 NOVEMBER 13
1ST DECEMBER 13 003 EW 1 NOVEMBER 1310 selected lines.
-
Note: I'll have to deal with a database 8i on this one...
Here is a simplified table & data:
The actual data are the result of a query and has about 200K lines, but this should be enough to solve my problem... It contains a list of commands and the steps that each order has to pass before a product is finished. There is also the date of beginning and end for each step.CREATE TABLE steps ( item_id CHAR(25) , ord_nbr CHAR(10) , sub_nbr CHAR(3) , step_nbr CHAR(4) , start_date DATE , finish_date DATE ); INSERT INTO steps VALUES ('A','0000000001','001','0010',TO_DATE('01/01/2011','mm/dd/yyyy'),TO_DATE('01/02/2011','mm/dd/yyyy')); INSERT INTO steps VALUES ('A','0000000001','001','0020',TO_DATE('01/03/2011','mm/dd/yyyy'),TO_DATE('01/03/2011','mm/dd/yyyy')); INSERT INTO steps VALUES ('A','0000000001','001','0030',TO_DATE('01/05/2011','mm/dd/yyyy'),TO_DATE('01/06/2011','mm/dd/yyyy')); INSERT INTO steps VALUES ('A','0000000001','002','0010',TO_DATE('01/01/2011','mm/dd/yyyy'),TO_DATE('01/02/2011','mm/dd/yyyy')); INSERT INTO steps VALUES ('A','0000000001','002','0020',TO_DATE('01/04/2011','mm/dd/yyyy'),TO_DATE('01/04/2011','mm/dd/yyyy')); INSERT INTO steps VALUES ('A','0000000001','002','0030',TO_DATE('01/06/2011','mm/dd/yyyy'),TO_DATE('01/07/2011','mm/dd/yyyy')); INSERT INTO steps VALUES ('B','0000000002','001','0005',TO_DATE('01/10/2011','mm/dd/yyyy'),TO_DATE('01/12/2011','mm/dd/yyyy')); INSERT INTO steps VALUES ('B','0000000002','001','0025',TO_DATE('01/18/2011','mm/dd/yyyy'),TO_DATE('01/19/2011','mm/dd/yyyy'));
My ultimate goal is to be able to calculate the product time (days) expected between steps. My first step to get what was:
This allows me to bring to the date of completion of the previous stage, while in the next level of the query, I get the difference between the previous step finishing and the present stage from give me the waiting time.SELECT s.* , LAG(s.finish_date) OVER ( ORDER BY s.item_id , s.ord_nbr , s.sub_nbr , s.step_nbr ) AS last_step_finished FROM steps s
The only problem is, I need for the query return null for the LAG function if the line is the first step in an agenda - a single order is given by ord_nbr + sub_nbr - because I won't be calculate the time between the end of another way and the beginning of another. I will assume that there are no queues in any order. So, I guess I could return NULL at this level, or at a higher level, simply ignore the column last_step_finished if I determine that the rank be the beginning of an order, but whatever it is, I have some difficulty to reconstruct the code to determine if a line is the first step in an order.
My first thought is that the solution will look something like:SELECT s.* , CASE WHEN --we're on the first step of an order THEN NULL ELSE LAG(s.finish_date) OVER ( ORDER BY s.item_id , s.ord_nbr , s.sub_nbr , s.step_nbr ) END AS last_step_finished FROM steps s
Hello
Thanks for being so clear on your version and display the sample data; This is really useful!
Don't forget to post the exact results you want from these data.You don't want to ORDER BY all these columns; you want to PARTITION BY som of them, instead, like this:
SELECT s.* , LAG (s.finish_date) OVER ( PARTITION BY s.item_id , s.ord_nbr , s.sub_nbr ORDER BY s.step_nbr ) AS last_step_finished FROM steps s
The output of this product that is:
ITEM_ID ORD_NBR SUB STEP START_DAT FINISH_DA LAST_STEP ------- ---------- --- ---- --------- --------- --------- A 0000000001 001 0010 01-JAN-11 02-JAN-11 A 0000000001 001 0020 03-JAN-11 03-JAN-11 02-JAN-11 A 0000000001 001 0030 05-JAN-11 06-JAN-11 03-JAN-11 A 0000000001 002 0010 01-JAN-11 02-JAN-11 A 0000000001 002 0020 04-JAN-11 04-JAN-11 02-JAN-11 A 0000000001 002 0030 06-JAN-11 07-JAN-11 04-JAN-11 B 0000000002 001 0005 10-JAN-11 12-JAN-11 B 0000000002 001 0025 18-JAN-11 19-JAN-11 12-JAN-11
If this isn't what you want, move some of the columns of the PARTITION BY clause from the ORDER BY clause.
PARTITION OF x, y, z is the analytical consideration of the aggregation GROUP BY x, y, z. This means that each separate combination of x, y and z will be considered to be a clean world, which do not interact with other values of x, y or z. On the first line of each partition, LAG return the NULL value, exactly as you wish.
Sorry, I don't have Oracle 8 to test, but I'm sure that LAG has not changed since Oracle 8.1.Moreover, the CHAR data type is nothing trouble. Use rather VARCHAR2.
-
by using the LAG() and MIN() functions
So, I try to get the smallest number in a column of an alias I use LAG() in. I know, which makes no sense, so here's what im trying to do with a SQL statement:
Select MIN (NUM1 - lag (num1, 1, 0)) over (ORDER BY NUM1) AS J_LAG ORDER BY HEY HEY
Basically I want the smallest number of the column that I run the lag function on. When I try to it says, ' ORA-30484: lack of specification of the window for this function. I tried to put in brackets the minutes like this: MIN (NUM1 - lag (num1, 1, 0)) and as follows: MIN (NUM1 - lag (num1, 1, 0) over (ORDER BY NUM1)) and none of them does not seem to work.
Any ideas?
-Joshualike this ?? Select Min(hey) From (Select num1 - lag(num1,1,0) over(ORDER BY NUM1) As hey From J_LAG)
-
Dear masters,
Oracle version: 11.2.0.2.0
I have a table called price_detail where the data is there in the format below
Sell_date(mm/dd/yyyy)
Dealer_Price
Discount
Net price
Net_Price_before_discount
01/01/2013
100
10
02/01/2013
120
20
03/01/2013
200
10
04/01/2013
100
20
05/01/2013
120
10
06/01/2013
210
30
07/01/2013
140
40
08/01/2013
150
10
09/01/2013
200
20
10/01/2013
100
10
11/01/2013
120
30
12/01/2013
140
20
In my program, I am passing a date range (for this example say entry date between 04/01/2013 09/01/2013), I need to calculate the NET_PRICE and the NET_PRICE_BEFORE_DISCOUNT for a given date range
Sell_date(mm/dd/yyyy)
Dealer_Price
Discount
Net price
Net_Price_before_discount
01/01/2013
100
10
02/01/2013
120
20
03/01/2013
200
10
04/01/2013
100
20
70
100
05/01/2013
120
10
80
190
06/01/2013
210
30
200
70
07/01/2013
140
40
120
80
08/01/2013
150
10
140
200
09/01/2013
200
20
170
120
10/01/2013
100
10
11/01/2013
120
30
12/01/2013
140
20
Net = Dealer_price - Discount price (of the 3rd day after the date of the day, so if we are calculating for 04/01/2013 then delivery must come from 06/01/2013)
Net_ Price_ before_ discount = Dealer_price (of the 3rd day before the current day, so if we are calculating for 04/01/2013 then the Dealer_price must come from 02/01/2013) - Discount
I can achieve this LEAD and functions LAG problem I'm facing is that I need to calculate it only for a date range and some values (as shown above) fall not going so here it is coming as 0.
- for example when I am Net_price calculation for the 09/01/2013, the discount is from 11/01/2013, but as in my case clause I have a widow who allows me to get data only between 01/04/2013 and on 09/01/2013, the discount is coming up as 0.
It's really complicated for me to achieve.
Please suggest.
AB
Every time that you give examples of data give as CREATE TABLE and INSERT QUERIES or the WITH clause. Its easy when its this way rather than the data in a structure of table posted by you.
You can use LEAD and LAG function like that. You must specify the OFFSET value to meet your need.
with t
as
(
Select to_date (' 01 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 100, 10 double discount
Union of all the
Select to_date (' 02 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 120, 20 double reduction
Union of all the
Select to_date (' 03 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 200, 10 double discount
Union of all the
Select to_date (' 04 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 100, 20 double reduction
Union of all the
Select to_date (' 05 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 120, 10 double discount
Union of all the
Select to_date (' 06 / 01/2013 ', ' dd/mm/yyyy') sell_date, 210 dealer_price, 30 double discount
Union of all the
Select to_date (' 07 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 140, 40 double reduction
Union of all the
Select to_date (' 08 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 150, 10 double discount
Union of all the
Select to_date (' 09 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 200, 20 double reduction
Union of all the
Select to_date (' 10 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 100, 10 double discount
Union of all the
Select to_date (' 11 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 120, 30 double discount
Union of all the
Select to_date (' 12 / 01/2013 ', ' dd/mm/yyyy') sell_date, dealer_price 140, 20 double reduction
)
Select sell_date
dealer_price
discount
, case when sell_date between to_date (' ' 04 / 01/2013 ', ' dd/mm/yyyy ') and
TO_DATE (' 09 / 01/2013 ', ' dd/mm/yyyy "")
then dealer_price - lead (2 discount) (sell_date order)
Another null
end net_price
, case when sell_date between to_date (' ' 04 / 01/2013 ', ' dd/mm/yyyy ') and
TO_DATE (' 09 / 01/2013 ', ' dd/mm/yyyy "")
then lag (dealer_price, 2) during delivery (order of sell_date).
Another null
end net_price_before_discount
t;
Output...
SELL_DATE DEALER_PRICE NET_PRICE NET_PRICE_BEFORE_DISCOUNT DISCOUNT
--------- ------------ -------- --------- -------------------------
1ST JANUARY 13 100 10
2 JANUARY 13 120 20
3 JANUARY 13 200 10
4 JANUARY 13 100 20 70 100
5 JANUARY 13 120 10 80 190
6 JANUARY 13 210 30 200 70
7 JANUARY 13 140 40 120 80
8 JANUARY 13 150 10 140 200
9 JANUARY 13 200 20 170 120
10 JANUARY 13 100 10
11 JANUARY 13 120 30
JANUARY 12, 13 140 20
12 selected lines
-
help with LAG () AND dates
I have at this moment the following query
What I've noticed, is that the LAG function is kind of what I want but not exactly. Let's say that I have given for the hours of 12: 00, 01:00, 02:00, 03:00 04:00, 05:00, 06:00, 07:00, 08:00, 09:00, 10:00, 11:00, 12:00 and the time is 12:00, the LAG function goes back to 12 h, which is what he should do.SELECT "DATE", "CELL_SITE", "LASTV_ATTCNT", "LASTV_ATTCNT2", "LASTV_BLKCNT", "LASTV_DRPCNT", "V_ATT_CNT", "V_CUST_BLK_CNT", "V_DRP_CALL_CNT", "LASTD_ATTCNT", "LASTD_BLKCNT", "LASTD_DRPCNT", "D_ATT_CNT", "D_CUST_BLK_CNT", "D_DRP_CALL_CNT" FROM ( SELECT DATE, CELL_SITE, LAG (SUM (V_ATT_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTV_ATTCNT", LAG (SUM (V_CUST_BLK_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTV_BLKCNT", LAG (SUM (V_DRP_CALL_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTV_DRPCNT", LAG (SUM (D_ATT_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTD_ATTCNT", LAG (SUM (D_CUST_BLK_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTD_BLKCNT", LAG (SUM (D_DRP_CALL_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTD_DRPCNT", SUM (V_ATT_CNT) AS "V_ATT_CNT", SUM (V_CUST_BLK_CNT) AS "V_CUST_BLK_CNT", SUM (V_DRP_CALL_CNT) AS "V_DRP_CALL_CNT", SUM (D_ATT_CNT) AS "D_ATT_CNT", SUM (D_CUST_BLK_CNT) AS "D_CUST_BLK_CNT", SUM (D_DRP_CALL_CNT) AS "D_DRP_CALL_CNT" FROM DMSN.DS3R_FH_1XRTT_FA_LVL_KPI WHERE DATE > (SELECT MAX (DATE) FROM DMSN.DS3R_FH_1XRTT_FA_LVL_KPI) - 2 GROUP BY DATE, CELL_SITE) WHERE DATE >= (SELECT MAX (DATE) - NUMTODSINTERVAL (12, 'HOUR') FROM DMSN.DS3R_FH_1XRTT_FA_LVL_KPI)
but lets say that I have given for 12 h, 01:00, 02:00, 03:00 04:00, 05:00, 07:00, 08:00, 09:00, 10:00, 11:00, 12:00, but it me MISSING at 06:00 (no data from 06:00). The lag function now back at 23:00 instead of 12 AM because the time 06:00 is missing.
If I have data for 12: 00 01:00, 02:00, 03:00 04:00, 07:00, 08:00, 09:00, 10:00, 11:00, 12:00 and am MISSING 05:00 and 06:00, the data will return to 22:00 then and not only from 12: 00.
Can I prevent this and always just come back in 12 hours?
Published by: k1ng87 on April 25, 2013 13:27Hello
k1ng87 wrote:
... LAG (SUM (V_ATT_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTV_ATTCNT", LAG (SUM (V_CUST_BLK_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTV_BLKCNT", LAG (SUM (V_DRP_CALL_CNT), 24) OVER (PARTITION BY BSM_NM ORDER BY DATE) AS "LASTV_DRPCNT", ...
Since you want to so many columns of the same previous row, it would be probably easier and more effective to make a self-join, rather than so many functions of SHIFT.
What I've noticed, is that the LAG function is kind of what I want but not exactly. Let's say that I have given for the hours of 12: 00, 01:00, 02:00, 03:00 04:00, 05:00, 06:00, 07:00, 08:00, 09:00, 10:00, 11:00, 12:00 and the time is 12:00, the LAG function goes back to 12 h, which is what he should do.
You always pass 24 as 2nd argument offset; What does "Return the value of the line 24 of the precding." If there is a line for each hour, the current line is from 12:00, then wouldn't 24 ranks back would be from 12:00 yesterday, not 12 AM? Maybe you wanted to spend 12, not 24, as the second argument of LAG. I'll assume you really want the 24 line rom now on, but the technique is the same that that number either 24 or 12.
but lets say that I have given for 12 h, 01:00, 02:00, 03:00 04:00, 05:00, 07:00, 08:00, 09:00, 10:00, 11:00, 12:00, but it me MISSING at 06:00 (no data from 06:00). The lag function now back at 23:00 instead of 12 AM because the time 06:00 is missing.
If I have data for 12: 00 01:00, 02:00, 03:00 04:00, 07:00, 08:00, 09:00, 10:00, 11:00, 12:00 and am MISSING 05:00 and 06:00, the data will return to 22:00 then and not only from 12: 00.
Can I prevent this and always just come back in 12 hours?
A self-join would handle this automatically: it will look for the corresponding line, without regard for other lines may be present or absent.
If you really had to do with the analytical functions, you can use MIN or FIRST_VALUE with a window of the range:
RANGE BETWEEN 1 + (.5 / 24) PRECEDING AND 1 - (.5 / 24) PRECEDING
DATE when you ORDER BY a column (do not call ' DATE'), the units are 1 day, so 1 + (.5/24) days ago is 24.5 hours; in other words, the window includes only DATES between 24.5 and 23.5 hours.
If, for some reason, you really want to call LAG, so you could do an outer join to ensure that a row had been present for each of the previous 24 hours.
I hope that answers your question.
If not, post a small example data (CREATE TABLE and only relevant columns, INSERT statements) and also publish outcomes from these data.
Explain, using specific examples, how you get these results from these data.
Always say what version of Oracle you are using (for example, 11.2.0.2.0).
See the FAQ forum {message identifier: = 9360002} -
With the help of lag and grade in the same query
Hello
I'm trying to find out the time difference between the memberships peoples, as well as the order in which these memberships are in. So far, I have added in a release status of work on the order, in that the accessions were created, but now want to look at the difference between the dates returned. The SQL, I used is:
SELECT owner_party_id,
mem_number,
support_id,
mem_start_date,
Rank() over (PARTITION BY owner_party_id ORDER BY mem_start_date ASC) MEMBERSHIP_SEQUENCE
OF membership_all
WHERE version_type = "NEWS".
AND owner_party_id IN ('65051', '65051', '65348', '65348', '65607' 65607', 65607')
to get:
"OWNER_PARTY_ID" | "' MEM_NUMBER ' | "' SUPPORT_ID ' | "' MEM_START_DATE ' | "" MEMBERSHIP_SEQUENCE ".
65051 | 318874751 | 8014747 | 1ST MARCH 10 | 1
65051 | 412311060 | 21502883 | 15 AUGUST 12 | 2
65348 | 308672459 | 3526913 | MAY 1, 10. 1
65348 | 409951130 | 20950524 | 18 JUNE 12 | 2
65607 | 315830192 | 7510133 | MAY 17, 10 | 1
65607 | 406448110 | 20024246 | MARCH 16, 12. 2
65607 | 409738130 | 20903556 | JUNE 14, 12. 3
Now I want to calculate the difference between the starting dates of each of the groups owner_party_id, in order to get something like this:
OWNER_PARTY_ID | MEM_NUMBER | SUPPORT_ID | MEM_START_DATE | MEMBERSHIP_SEQUENCE | Diff
65051 | 318874751 | 8014747 | 1st March 10 | 1.
65051 | 412311060 | 21502883 | 15 August 12 | 2. 898
65348 | 308672459 | 3526913 | May 1, 10. 1
65348 | 409951130 | 20950524 | 18 June 12 | 2. 779
65607 | 315830192 | 7510133 | May 17, 10 | 1
65607 | 406448110 | 20024246 | March 16, 12. 2. 669
65607 | 409738130 | 20903556 | June 14, 12. 3. 90
I think I need to use the Lag function, but I'm not sure if it can be linkited looking at the data within a group id of owner of party, that it would be foolish to calculate the difference in dates for the two different owner group ID.
Any advice much appreciated.
Thank you
Published by: 992871 on March 9, 2013 23:34Maybe NOT TESTED!
SELECT owner_party_id, mem_number, support_id, mem_start_date, RANK() OVER (PARTITION BY owner_party_id ORDER BY mem_start_date) MEMBERSHIP_SEQUENCE, mem_start_date - LAG(mem_start_date,1) OVER (PARTITION BY owner_party_id ORDER BY mem_start_date) diff FROM membership_all WHERE version_type = 'CUR' AND owner_party_id IN ('65051','65051','65348','65348','65607','65607','65607')
Concerning
Etbin
Maybe you are looking for
-
IMPORT OF CUP FINAL DOSNT WORKS
HAVE A PROBLEM W / IMPORT! WATCH THIS VIDEO https://www.YouTube.com/watch?v=N2D8chQ2g5E & feature = youtu.be
-
After the last update of the operating system and iMovie it seems I can't create a movie in the PAL standard. Can anyone help?
-
Plastic protective cover on the lid of the M40
Hi, I was wondering if it is allowed to leave the plastic protection on the lid of the laptop Toshiba M40 or should it be removed before using it? It would lead to an accumulation of static electricity, which could cause problems? Thank you.
-
iTunes library disappeared after El Capitan upgraded
After the upgrade of the OS Yosemtie to El Capitan, my 6 000 more than songs in my iTunes library are missing and not appearing is not in iTunes. My hard drive reflects a lot of space is used by 'audio' so I guess that the songs are somewhere and I
-
I get white horizontal stripes in printing or copy, black & white or color on my HP L7580. I tried cleaning, rebooting and everything I can think of. Does anyone have a suggestion? Thank you.