Select Row immediately previous and following a date range
I have a query which returns two values within a given date range (colA, colB). This works great. However, I also need to return (in a separate query) the entries immediately previous and following this current date range (same two values).
I am more familiar with MySQL where the query would include an "Order by date desc limit 1" for the row previous to the original query or "Order by date asc limit 1" for the row following the original query.
What is the best way to return these rows within Oracle?
Hi,
This is an example of a Top-N Query, where you want to pick N items (N=1 in this case) from the top of an ordered list.
This problem is a little trickier, because you want to pick from two lists, the rows before the specieifed date range (in descending order) and the rows after the range.
The easiest way might be a UNION of two separate queries, using WHERE ROWNUM = 1 in each one.
The solution below is easier to generalize, e.g. if you want the first and last row from each department.
WITH
e AS
SELECT empno, ename, hiredate
, ROW_NUMBER () OVER
( ORDER BY CASE
WHEN hiredate < TO_DATE ( '01-JAN-1982'
, 'DD-MON-YYYY'
) -- Start of date range
THEN hiredate
END
DESC NULLS LAST
) AS pre_num
, ROW_NUMBER () OVER
( ORDER BY CASE
WHEN hiredate > TO_DATE ( '31-DEC-1982'
, 'DD-MON-YYYY'
) -- End of date range
THEN hiredate
END
) AS post_num
FROM scott.emp
SELECT empno, ename, hiredate
FROM e
WHERE pre_num = 1
OR post_num = 1
;Results (last hire before 1982 and first hire after 1982):
EMPNO ENAME HIREDATE
7788 SCOTT 19-APR-87
7900 JAMES 03-DEC-81
Similar Messages
-
Hi,
;WITH CTE AS
( SELECT tblFuelCostDetails.TripId, tblFuelCostDetails.PurchaseDate, tblPetrolPumps.PumpName as Pump
FROM tblPetrolPumps INNER JOIN
tblFuelCostDetails ON tblPetrolPumps.PumpId = tblFuelCostDetails.PumpId
SELECT distinct TripID, PurchaseDate,DENSE_RANK() OVER (ORDER BY TripID) AS RowNumber,
STUFF((SELECT ', '+Pump FROM CTE P2 WHERE P1.TripID = P2.TripID AND P1.PurchaseDate = P2.PurchaseDate
FOR XML PATH('')),1,1,'') AS Pump
FROM CTE P1
This query output is,
TripID
PurchaseDate
RowNumber
Pump
73
1/15/2014
1
N.R, Masranga
74
1/16/2014
2
N.R
75
1/12/2014
3
JK
76
1/13/2014
4
YUJ
77
1/14/2014
5
UYI
How can i get RowNumber between 2 and 4Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules (you did not). Temporal
data should use ISO-8601 formats (you failed this basic IT standard! Shame on you!). Code should be in Standard SQL as much as possible and not local dialect.
Did you know that putting “tbl-” is such a bad coding practice it has name? You actually Tibbled!
>> I am trying to load time dimension in a specific order <<
A table has no ordering by definition. Let me say that again, so you will hear this: A table has no ordering by definition. You have completely missed the foundations of RDBMS.
Your code is also bad. Why did you rename “pump_name” (a valid data element name) to “pump” (vague and invalid)? Why do you think naming a CTE to “CTE” is informative?
Why are you destroying First Normal Form with XML??? Are you smarter than Dr. Codd? I would fire you for this kind of sloppy coding.
Do you know how rate SELECT DISTINCT is in a good schema? We usually use a key in the queries so there are not redundant rows. But since we have no DDL and no sample data, we cannot help you clean up this mess. Your query is simply this:
SELECT F.trip_nbr, F.purchase_date, P.pump_name
FROM Petrol_Pumps AS P, Fuel_Cost_Details AS F
WHERE P.pump_nbr = F.pump_nbr;
Now pass the result set to a presentation layer, as per any tiered architecture. Since we have no logical rule for the subset you want, adding a DENSE_RANK() may not do what you want. Why order by trip_nbr? This is a tag number, not part of a sequence.
--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 -
Select from 2 tables and insert same data into 2 other tables(BPEL Process)
Hi All,
Please suggest me how to select from 2 tables and insert the same data into 2 tables. I am successful in selecting data from 2 tables, but i am not able to insert the same data into 2 other tables. There is foreign key constraint between 2 tables.
Thanks in Advance,
MAHI have created DB Adapter for selecting from 2 tables and also DB adapter for insert and i have created parent child relationship between 2 tables.
I am getting this error
<Faulthttp://schemas.xmlsoap.org/soap/envelope/>
<faultcode>env:Server</faultcode>
<faultstring>com.oracle.bpel.client.delivery.ReceiveTimeOutException: Waiting for response has timed out. The conversation id is 6f3fe20c1b031057:-6cc7dfb5:11b8bf5fbe1:-7fa4. Please check the process instance for detail.</faultstring>
</Fault> -
Hi
I am creating a simple design studion project request form where the user can enter how many photographs need to be ordered. I am calling this field 'NumImages'. Then once the data is entered, another field (I am calling this NumDaysImage) will be calculated based on the fact that no more than 5 photographs can be shot per day. So, 1-5 photos = 1 day. 6-10 photos = 2 days. 11-15 photos = 3 days etc. I do not need to calculate part days, so 6 photos is the same as 10 i.e. 2 days.
Once I have calcuated 'NumDaysImage', I then need to calculate an end date called 'DateDue'. The start date is entered by the user in the field 'DateStart'.
I know this is not going to be easy, but how can I calculate 'DateDue' based on a Mon-Fri working week, and ideally excluding UK public holidays?
Also on the form is a value 'NumDays' that is the number of days for designing the brochure for the photos. This value I have calculated already, but it will need to be added to 'NumDaysImage' to get a total number of production days that is then used to calculate 'DateDue'.
Any help will be greatly appreciated. Thanks.JavaScript has the Math.ceil method which rounds up a number to the next integer if it is not an integer.
Dates are more complicated calculation as the starting date needs to be converted to a number and then one can calculate the ending date and test that date to see if is a Sunday or Saturday. Do intervening weekends add to the number of days for processing. -
How to delete a selected row from datagrid and how to create a datagrid popup
hi friends,
I am new to flex.i am doing a flex4 application,i need help for this.
i am having a data grid with columns.i have two questions.
Ques 1: when i selected a partiuclar row from a datagrid and click delete button means that record will delete from the datagrid and DTO from the cloud tables also.
Ques 2: when i save the data grid values using save button means that data will store in respective cloud DTO which is related to the datagrid,
My requirement is i am using a search button when i click the search button it will show a datagrid that datagrid will contain the previous datagrid datas which is saved in the cloud.
REQUIREMENT example: first screen: i am using with data grid 3 columns (Student Roll number ,Student Name,Student pecentage)---->save--->data will store in cloud DTO.
Second screen: search button ----> it need show datagrid popup.it will have data which we saved in the first screen with same columns(Student Roll number ,Student Name,Student pecentage).
This is my requirement.
Any suggession welcome.
Thanks in advance.
B.VenkatesanLets break the problem statement in multiple steps
1. We need a way to know the selection on all rows.
2. We need the association of the checkBox with the data
The solution is to use a arrayCollection/array that holds all the instances created for checkbox.This collection should be a property of component containing the datagrid. We need to use a custom component implementation or inline ItemRenderer. The way you have used is called dropinItemRenderer. Preferaly use custom component implementation and add the instance to the arrayCollection at CreationComplete. Make sure you use addItemAt so that you add the instance in the same row as the data. To get rowIndex the custom Checkbox should implement IDropInListItemRenderer. You could iterate this collection to check all the instances that are checked.
Note: This is the approach considering your dataprovider doesnt have a selection field.
Nishant -
How to delete a Selected row from datagrid and how to create a datagrid popup with saved values
hi friends,
I am new to flex.i am doing a flex4 application,i need help for this.
i am having a data grid with columns.i have two questions.
Ques 1: when i selected a partiuclar row from a datagrid and click delete button means that record will delete from the datagrid and DTO from the cloud tables also.
Ques 2: when i save the data grid values using save button means that data will store in respective cloud DTO which is related to the datagrid,
My requirement is i am using a search button when i click the search button it will show a datagrid that datagrid will contain the previous datagrid datas which is saved in the cloud.
REQUIREMENT example: first screen: i am using with data grid 3 columns (Student Roll number ,Student Name,Student pecentage)---->save--->data will store in cloud DTO.
Second screen: search button ----> it need show datagrid popup.it will have data which we saved in the first screen with same columns(Student Roll number ,Student Name,Student pecentage).
This is my requirement.
Any suggession welcome.
Thanks in advance.
B.VenkatesanLets break the problem statement in multiple steps
1. We need a way to know the selection on all rows.
2. We need the association of the checkBox with the data
The solution is to use a arrayCollection/array that holds all the instances created for checkbox.This collection should be a property of component containing the datagrid. We need to use a custom component implementation or inline ItemRenderer. The way you have used is called dropinItemRenderer. Preferaly use custom component implementation and add the instance to the arrayCollection at CreationComplete. Make sure you use addItemAt so that you add the instance in the same row as the data. To get rowIndex the custom Checkbox should implement IDropInListItemRenderer. You could iterate this collection to check all the instances that are checked.
Note: This is the approach considering your dataprovider doesnt have a selection field.
Nishant -
Previous and Prior Year Date Values
How do I get the Previous, Prior year month and Prior year previous month values from a given date?
Ex: Input would be: 05/01/2008
The output should be:
05/01/2008 - Current Month
04/01/2008 - Previous Month for the Current Year
05/01/2007 - Prior year current Month
04/01/2007 - Prior Year Previous Month
Please let me know..Hi,
Then you'll probably do a self-join. In one copy of the table, you'll get the data from date d1, and in the other copy, you'll get the data from date ADD_MONTHS (d1, -12).
If, ultimately, you are going to show four sets of figures (from four different rows representing four different dates) on the same output line, then you may find it more convenient to do a pivot rather than a self-join. Search for the buzz word "pivot" and you'll get lots of examples. You might start by selecting four rows:
WHERE dt IN
( d1
, ADD_MONTHS (d1, -1)
, ADD_MONTHS (d1, -12)
, ADD_MONTHS (d1, -13)
) ...and then pivoting that data into four columns:
SELECT ...
, MAX (CASE WHEN dt = d1 THEN val END) AS this_month
, MAX (CASE WHEN dt = ADD_MONTHS (d1, -1) THEN val END) AS one_month_ago
, MAX (CASE WHEN dt = ADD_MONTHS (d1, -12) THEN val END) AS one_year_ago
, MAX (CASE WHEN dt = ADD_MONTHS (d1, -13) THEN val END) AS thirteen_months_ago
... -
How can I select rows of cells and merge them vertically into one cell in each column?
I'm working in CS4 and need to be able to select 2 to 6 rows of cells (with many columns) in a table and then merge the selected cells vertically into one cell in each column. A few cells in the chart will not need to merge so I must select the ones that do. I have almost 100 pages of charts with cells that need merged this way by Tuesday. Please help!
Top chart example needs to change to the bottom example.
Header 1
Header 2
Header 3
Header 4
Header 5
Header 6
100
600
300
600
20000
120000
2000
500
400
50000
10000
5000
3000
200
700
67
122
600
900
100
2
7
123
1110
Header 1
Header 2
Header 3
Header 4
Header 5
Header 6
100
500
200
100
600
400
700
900
300
5000
30000
2
600
10000
67
7
20000
2000
122
123
120000
5000
600
1110SmartCellMerge may help you:
http://www.indiscripts.com/post/2012/04/improve-the-way-you-merge-cells-in-indesign
@+
Marc -
How to check the time taking to extract rows from source and time load data into destination
Hi,
Recently I have started working on Optimizing an SSIS package in 2012. The package reads data from AS 400 server and load into SQL Server table.. No transformations are being used in the package. only ADO.Net Source and OLE DB Destination are using in the
package.
The SSIS package is extracting 6500 rows and loading into database per batch. This process is taking 18 seconds. I would like to know out of 18 secs how much time is being used only to extract data from the source and how much time is taking to write the
data to the database per each batch.
Any thoughts be greatly appreciated...
Thanks,
Venu.Hello
We need more information regarding your system. If you are using SQL 2014 then you can use the new DMV
sys.dm_exec_query_profiles which is doing this exactly. Check out this URL: http://msdn.microsoft.com/en-us/library/dn223301.aspx
While executing your SSIS project you can examine each and every process and get the percentage it already did and all the information regarding it.
Ronen Ariely
[Personal Site] [Blog] [Facebook] -
I was attempting to restore music to my new IPhone. The music was once on an Ipod that I had. I selected backup restore thinking I would get the music. I lost all my contacts, music, pictures, text messages, and everything. What can I do to get back the items lost. Please help???
Restore an iPhone backup.
-
Min and max from date range span..
Hi All,
Here is the problem, we have the data like below and
MEMBER_NO YMDEFF YMDEND
5400 01-MAY-99 30-JUN-99
5400 01-JUL-99 31-DEC-99
5400 01-JAN-00 31-DEC-00
5400 01-JAN-01 31-JAN-01
5400 01-FEB-01 30-APR-01
5400 01-MAY-01 31-OCT-02
5400 01-NOV-02 31-DEC-03
5400 01-JAN-04 31-JAN-04
5400 01-FEB-04 29-FEB-04
3Y00 01-JAN-02 23-JUL-02
3Y00 24-JUL-02 31-OCT-02
3Y00 01-NOV-02 30-APR-03
3Y00 01-MAY-03 31-OCT-03
3Y00 01-JAN-04 31-JUL-04
3Y00 01-FEB-06 30-NOV-06
3Y00 01-DEC-06 31-DEC-99We want the output will be like this it is group by the member_no according to the time span. it is like if the consecutive rows are in range of continuous dates than it become a one span and if there is any breaks in between then that will be in a separate span.
MEMBER_NO min_YMDEFF max_YMDEND
5400 01-MAY-99 29-FEB-04
3Y00 01-JAN-02 31-JUL-04
3Y00 01-FEB-06 31-DEC-99Thanks in advanceIn code this story becomes:
SQL> create table mytable
2 as
3 select '5400' member_no, date '1999-05-01' ymdeff, date '1999-06-30' ymdend from dual union all
4 select '5400', date '1999-07-01', date '1999-12-31' from dual union all
5 select '5400', date '2000-01-01', date '2000-12-31' from dual union all
6 select '5400', date '2001-01-01', date '2001-01-31' from dual union all
7 select '5400', date '2001-02-01', date '2001-04-30' from dual union all
8 select '5400', date '2001-05-01', date '2002-10-31' from dual union all
9 select '5400', date '2002-11-01', date '2003-12-31' from dual union all
10 select '5400', date '2004-01-01', date '2004-01-31' from dual union all
11 select '5400', date '2004-02-01', date '2004-02-29' from dual union all
12 select '3Y00', date '2002-01-01', date '2002-07-23' from dual union all
13 select '3Y00', date '2002-07-24', date '2002-10-31' from dual union all
14 select '3Y00', date '2002-11-01', date '2003-04-30' from dual union all
15 select '3Y00', date '2003-05-01', date '2003-12-31' from dual union all
16 select '3Y00', date '2004-01-01', date '2004-07-31' from dual union all
17 select '3Y00', date '2006-02-01', date '2006-11-30' from dual union all
18 select '3Y00', date '2006-12-01', date '2099-12-31' from dual
19 /
Tabel is aangemaakt.
SQL> select member_no
2 , min(ymdeff) "min_YMDEFF"
3 , max(ymdend) "max_YMDEND"
4 from ( select t.*
5 , sum(consecutive) over (partition by member_no order by ymdeff) sum_consecutive
6 from ( select member_no
7 , ymdeff
8 , ymdend
9 , sign(ymdeff - lag(ymdend,1,ymdeff-2) over (partition by member_no order by ymdeff) - 1) consecutive
10 from mytable
11 ) t
12 )
13 group by member_no
14 , sum_consecutive
15 order by 1, 2
16 /
MEMBER_NO min_YMDEFF max_YMDEND
3Y00 01-01-2002 00:00:00 31-07-2004 00:00:00
3Y00 01-02-2006 00:00:00 31-12-2099 00:00:00
5400 01-05-1999 00:00:00 29-02-2004 00:00:00
3 rijen zijn geselecteerd.Regards,
Rob. -
How do i get the data present in the selected row at run time in Multicolumn list box?
Hi,
I am using multicolumn list box with three columns and i am having OK button.
If the user selects particular row and then press ok then that row datas(that 3 values) has to get update in the file.
Can u tell me how to get that selected row values alone and also how to append the list box value at run time?
Thanks
MeenatchiYou can simply use the Value property of the MLBox to get the row selected & wire it to the Delete from array function with the Itemnames of the MLBox as the Input & Output of the Delate from array function.
See the attached VI.
- Partha
LabVIEW - Wires that catch bugs!
Attachments:
Dbl-click Row to get Data & Delete.vi 41 KB -
How do I get rid of 97] in Cookies and other website data
When I open Preferences/Privacy and select "Details" under "Cookies and other website data" the first entry which pops up is
97] plug-ins
If I highlight this entry and click remove, It is removed for perhaps 10 seconds, and then re-appears in the list.
1- What is this?
2- How do I get rid of it?
This is clearly a prvacy issue, or Apple would not be listing it in this listing with the associated warning.Linc Davis wrote:
Log out, then log back in while holding down the shift key after you enter your login password. Keep holding until the desktop appears. That will prevent third-party add-ons from loading. Try again to delete that item.
If you still can't delete it, and you still want to, proceed as follows.
Back up all data if you haven’t already done so. Before proceeding, you must be sure you can restore your system to the state it’s in now. If you skip this step, no one but you will be responsible for the consequences.
Quit Safari if it’s running.
Step 1
Select /Applications/Safari in the Finder and open the Info window. There’s a checkbox in that window labeled “Open in 32-bit mode.” If that box is checked, uncheck it. Close the window.
Hold down the option key and select Go > Library from the Finder menu bar (Lion) or open the Library subfolder of your home folder (pre-Lion). Delete the following items from the Library folder (some may not exist):
Caches/com.apple.Safari
Caches/Metadata/Safari
Saved Application State/com.apple.Safari.savedState
Leave the Finder window open. Try Safari again.
Step 2
If it still doesn’t work right, quit, go back to the Finder, and move the following file to the Desktop:
Safari/Bookmarks.plist
Then delete the following items (some may not exist):
Cookies/Cookies.binarycookies
Cookies/Cookies.plist
Preferences/com.apple.Safari.LSSharedFileList.plist
Preferences/com.apple.Safari.plist
Preferences/com.apple.Safari.RSS.plist
PubSub/Database
Safari
Try again. This time Safari should perform normally, but your settings will be lost. Select File > Import Bookmarks from the Safari menu bar. Import from the bookmarks file you moved to the Desktop. Recreate the rest of your Safari settings. You can then delete the old bookmarks file.
Note: This step will remove your Safari Extensions, if any, and their settings. If you choose to restore them, do so one at a time, testing after each to make sure you haven’t restored the problem.
If you don’t like the results of step 2, you can undo it completely by quitting Safari and restoring the items you deleted in that step from your backup, overwriting any that were created in their place. You don’t need to restore the files you deleted in step 1.
Ok... completed step1 with no change.
went on to "part of "step 2...
I kept the Bookmarks.plist, but then deleted the assortment of safari related Caches and Cookies
Cookies/Cookies.binarycookies
Cookies/Cookies.plist
(I found several entries in Cache, but forgot to write down which ones I deleted ... sorry.)
did not delete any of the preferences or the last two entries in your list above.
Tried again and "the perp" was still there. "Remove all" on the Details tab did not change things...
However, there were now only 2 entries -- the 97] AND my bank's entry (Chase)!
Going back to the main privacy tab and clicking "Remove all Website Data" this time DID remove the last two entries.
=====
Now when I open the details tab, (I run my own webserver as my home page) Safari showed ONLY the cache entry for my server, no cookies.
However, I then noticed something quite intersting.
I left the details tab open and pulled to the side (the joy of having a 27 inch iMac) and naviaged to Apple.com
and then to support and then logged in to here.
As I was doing this. the Details window first showed, "Apple.com" .. Cache, Cookies, Local Storage
but then virtually immediately poped up entries:
doubleclick.net ... Cache
edgekey.net ... Cache
google.com ... Cookies
Very interesting, both from the point of view that "details" was showing me what was happening in "real time."
And the fact that, even with zero external ads, the web site, Apple.com, was inserting entries in the cache for doubleclick.net and edgekey.net. I can "almost" understand the "google.com" cookie, ecept for the fact that the search engine selected in the tool bar is "bing."... as I said "interesting."
With this new "insight" on the Details screen, It may be possible to determine WHERE this 97] actually came from. However, I would still like an explanation of what it actually is.... since the "]" (right square bracket) character is evidently a "special character" for search engines -- google, Yaho and Bing all treat it the same way -- they ignor it.... even when the entire 3 character string is quoted -- "97]" -- the pages returned all are for entries with only 97 in them. -
How to edit selected rows in a datagrid?
Hi all,
I am new to flex and I would like to know how to edit
selected rows( through check boxes) in a data grid. As of now the
whole data grid becomes editable.
Regards
Saran.This is not simple in Flex 2.0.
You will need to use a custom itemRenderer.
Search the net, perhaps someone has a component or sample
close to what you want.
Tracy -
How to select row automatically in matrix (exp:automatic select row no 2)?
Hi
example i fill matrix row no 1 - 3 in serial number selection form or else (from database data)
and i want to automatic select row no 2
and i really have a big problem to do this
oQuant = edit text
oColumn = column
oForm = form
here some of my code
====================================
formID = pVal.FormUID
Set oForm = SBO_Application.Forms(formID)
Set oMatrix3 = oForm.Items.Item("5").Specific
Set oColumn3(3) = oMatrix3.Columns.Item("19")
Set oQuant(5) = oColumn3(3).Cells.Item(2).Specific
=====================================
i tried
oMatrix3.SelectRow 2, True, False
but it didn't work , it's said that not user defined item
oQuant(5).Active = True
it works but that not the select what i want
pls some one help me
i really need it right away
ThanksHi chetan
Thank You for your reply and yes i didn't write selection mode for my matrix
but when i tried both of these code it still didn't work (for information i'm using visual basic 6, so it has a different syntax about .net and VB6 - exp: for .net oMatrix.selectrow(2,true,false) , for VB6 oMatrix.selectrow 2,true,false )
oMatrix.SelectionMode = SAPbouiCOM.BoMatrixSelect.ms_Auto
oMatrix.SelectRow 2, True, False
oMatrix.SelectionMode = ms_Auto
oMatrix.SelectRow 2, True, False
is there any presiquities for selection mode ?? because I always have <b>warning</b> on oMatrix.selectionmode
"<b>Item - the item is not user defined item</b>"
Edit : it works when i created a form and select row no 2, but it didn't work with serial number selection form which the form is already exist in SBO (serial number selection is the form after klik add button in good issue form)
Thanks
Maybe you are looking for
-
Core dump while running jmf application
I am running a bit customised version of Transcode & Concat from JMF samples as a single application on Solaris 10. I got core dump while running the application. Any clue ? Below are the content from hs_err_pid#.out file. +#+ +# An unexpected error
-
I have checked with weblogic Server 8.1, supposing exposing Java Components as web services. I have checked with the examples.It is quite easily achievable. But what i want to know as what mentioned in http://www.javaworld.com/javaworld/jw-08-2004/jw
-
I have a multi-user windows based machine where both users have the same browser, search engine, plugins, applications, etc. I use this machine primarily as an entertainment system (ie. TV client/server using a TV Tuner card, Music & Video Player, et
-
I have a question about a correlation table and getting the results whether it is there or not. I've done this in SQL Server's product but haven't had success transferring it to ORACLE. Here is the situation: I have a table of visitors, a table of vi
-
Can you load Software on two computers?
Just wondering if I could load the desktop software on my work AND home computer?? or do I have to pick one.