Select records based on max(date)
Hi everyone,
I have a table (tbl_training) with training information-such as who took what training, when they took it, scores they received and other various stuff.
In this table, a person could have taken multiple training within the year. what i need to see in my results is, the last training the person took. I assume i am looking to query something that produces max(date_of_training) and maybe grouping my id_number. I have tried various combinations of sub-queries to no avail. Any help is welcomed.
So my data may look something like this:
id_number date_of_training score last_name first_name instructor rank
1234 01/01/09 50 doe john mr. hank sgt
1234 02/13/09 72 doe john mr. hank sgt
1234 01/31/09 60 doe john mr. hank sgt
5678 02/03/09 80 smith lisa mr. hank cpl
What i need returned in the query is:
1234 02/13/09 72 doe john mr. hank sgt
5678 02/03/09 80 smith lisa mr. hank cpl
Select id_number, date_of_training, score, last_name, first_name, instructor, rank
from tbl_training;
Thanks for the help in advance.
Try this code
select * from (
Select id_number, date_of_training, score, last_name, first_name, instructor, rank, row_number()over(partition by id_number order by date_of_training desc ) rn
from tbl_training)
where rn =1;
Similar Messages
-
How to select records based on Max/Min on different columns and group by
I have a table with 5 columns(a,b,c,d,e), i need to select records based on MAX(c),Max(D) and Min(e) group by a,b. i am trying using : select max(c),max(d),min(e) from table group by a,b. this is not working. its giving me 1 6 1
a b c d e
1 1 1 2 1
1 1 1 6 4
1 1 1 6 3
when i group by a,b i am expecting the record 1 6 3
Please help me with this.. Thanks in advance....Hi,
Welcome to the forum!
962163 wrote:
I have a table with 5 columns(a,b,c,d,e), i need to select records based on MAX(c),Max(D) and Min(e) group by a,b. i am trying using : select max(c),max(d),min(e) from table group by a,b. this is not working. its giving me 1 6 1
a b c d e
1 1 1 2 1
1 1 1 6 4
1 1 1 6 3
when i group by a,b i am expecting the record 1 6 3It looks to me like "1 6 1" is the correct answer. You're asking for the lowest value of e, and 1 is lower than 3.
Maybe you don't want MIN (e). Explain why you want 3 (that is, how you decided that 3 is the correct value for the last column) and someone will help you code it.
Edited by: Frank Kulash on Sep 28, 2012 6:17 PM
Whenever you have a problem, you should psot CREATE TABLE and INSERT statements for your sample data. That way, the people who want to help you can re-create the problem and test their ideas. It often helps to clarify the problem, too. since this is your first message, I'll do it for you:
CREATE TABLE table_x
( a NUMBER
, b NUMBER
, c NUMBER
, d NUMBER
, e NUMBER
INSERT INTO table_x (a, b, c, d, e) VALUES (1, 1, 1, 2, 1);
INSERT INTO table_x (a, b, c, d, e) VALUES (1, 1, 1, 6, 4);
INSERT INTO table_x (a, b, c, d, e) VALUES (1, 1, 1, 6, 3);
COMMIT; -
Select records based on monthly anniversary date
Hi,
I have a table with a date_added field and I want to select records based on the monthly anniversary date of this field.
eg. ID, Date_added
1, 10-DEC-2012
2, 11-NOV-2012
3, 10-MAR-2012
4, 28-FEB-2012
5, 30-DEC-2012
So For the 10th of Jan 2013, I would want to return records 1 and 3 only
I started looking at the extract function, but this soon falls down for records at the end of the month. For example, on the 28th Feb, I would also want to include records where the date_added day is the 29th, 30th or 31st. So, in the table above I would want to return records 4 and 5, but extract would only return 4.
Is there a simple function to do this month anniversary query - am I missing something very obvious? Or, do I need to write a query to explicitly cope with dates at the end of the month? So far I haven't found a sensible simple solution!
I'm using 11g
thanksI didn't look into leap year, but this should give you a starting point:
select *
from t
where 1 = case last_day(to_date(:target_date,'mmddyyyy'))
when to_date(:target_date,'mmddyyyy')
then case
when to_char(date_added,'dd') >= to_char(to_date(:target_date,'mmddyyyy'),'dd')
then 1
end
else case
when to_char(date_added,'dd') = to_char(to_date(:target_date,'mmddyyyy'),'dd')
then 1
end
end
/For example, target date is 1/10/2013:
SQL> variable target_date varchar2(8)
SQL> exec :target_date := '01102013';
PL/SQL procedure successfully completed.
SQL> with t as (
2 select 1 id,to_date('10-DEC-2012','dd-mon-yyyy') date_added from dual union all
3 select 2,to_date('11-NOV-2012','dd-mon-yyyy') from dual union all
4 select 3,to_date('10-MAR-2012','dd-mon-yyyy') from dual union all
5 select 4,to_date('28-FEB-2012','dd-mon-yyyy') from dual union all
6 select 5,to_date('30-DEC-2012','dd-mon-yyyy') from dual
7 )
8 select *
9 from t
10 where 1 = case last_day(to_date(:target_date,'mmddyyyy'))
11 when to_date(:target_date,'mmddyyyy')
12 then case
13 when to_char(date_added,'dd') >= to_char(to_date(:target_date,'mmddyyyy'),'dd')
14 then 1
15 end
16 else case
17 when to_char(date_added,'dd') = to_char(to_date(:target_date,'mmddyyyy'),'dd')
18 then 1
19 end
20 end
21 /
ID DATE_ADDE
1 10-DEC-12
3 10-MAR-12
SQL> And target date is 2/28/2013:
SQL> exec :target_date := '02282013';
PL/SQL procedure successfully completed.
SQL> with t as (
2 select 1 id,to_date('10-DEC-2012','dd-mon-yyyy') date_added from dual union all
3 select 2,to_date('11-NOV-2012','dd-mon-yyyy') from dual union all
4 select 3,to_date('10-MAR-2012','dd-mon-yyyy') from dual union all
5 select 4,to_date('28-FEB-2012','dd-mon-yyyy') from dual union all
6 select 5,to_date('30-DEC-2012','dd-mon-yyyy') from dual
7 )
8 select *
9 from t
10 where 1 = case last_day(to_date(:target_date,'mmddyyyy'))
11 when to_date(:target_date,'mmddyyyy')
12 then case
13 when to_char(date_added,'dd') >= to_char(to_date(:target_date,'mmddyyyy'),'dd')
14 then 1
15 end
16 else case
17 when to_char(date_added,'dd') = to_char(to_date(:target_date,'mmddyyyy'),'dd')
18 then 1
19 end
20 end
21 /
ID DATE_ADDE
4 28-FEB-12
5 30-DEC-12
SQL> SY. -
Select records based on the closest given time
Dear SQL gurus,
I have a table T1:
Name Null? Type
ID NOT NULL NUMBER(5)
MOMENT NOT NULL DATE [DD.MM.YYYY HH24:MI]
MEASUREMENT NOT NULL NUMBER(8,3)
Example (ID, MOMENT, MEASUREMENT)
-- START OF EXAMPLE --
9380 18.11.2000 03:45 17.6
9380 18.11.2000 04:30 17.3
9380 18.11.2000 05:45 16.8
9380 18.11.2000 06:15 16.8
9380 18.11.2000 07:00 16.2
9380 18.11.2000 07:30 16.2
9380 18.11.2000 08:15 16
9380 18.11.2000 08:45 15.7
9380 18.11.2000 09:30 15.4
9380 18.11.2000 10:00 15.4
9380 18.11.2000 11:15 15.4
9380 18.11.2000 11:45 15.4
9380 18.11.2000 12:30 15.4
9380 18.11.2000 13:00 15.4
9380 18.11.2000 13:45 15.4
--- END OF EXAMPLE --
How to select records based on the:
- time period specified by the day only [DD.MM.YYYY] - CONDITION 1
- with values for 6AM only, and if not available, with values closest to 6AM - CONDITION 2
(if the time gap in MOMENT field is too big, lets say > 5h then choose the average between the value before 6AM (ex. 4:15AM) and the value after the 6AM (ex. 9:45AM))
CONDITION 1 (something like): moment between '01.01.2005' and '31.12.2004' - this is OK
CONDITION 2: I do not know how to formulate, especially if 6AM value is not availabe, and I have to find the closest available value, or get the avergae from the two adjacent values.
Maybe cursor magic??? Thanks a lot for your help.
RadoAbout condition two, would the following select be of use to you? Picking the first record could be achived by rownum, analytic function, etc.
WITH t1 AS (SELECT 9380 id, TO_DATE('18.11.2000 03:45', 'dd.mm.yyyy hh24:mi') moment, 17.6 measurement
FROM dual
UNION
SELECT 9380 id, TO_DATE('18.11.2000 04:30', 'dd.mm.yyyy hh24:mi') moment, 17.3 measurement
FROM dual
UNION
SELECT 9380 id, TO_DATE('18.11.2000 05:45', 'dd.mm.yyyy hh24:mi') moment, 16.8 measurement
FROM dual
UNION
SELECT 9380 id, TO_DATE('18.11.2000 06:15', 'dd.mm.yyyy hh24:mi') moment, 16.8 measurement
FROM dual
SELECT id, moment, measurement, diff
FROM (SELECT id, moment, measurement,
moment - TO_DATE(TO_CHAR(moment, 'dd.mm.yyyy ') || '06:00', 'dd.mm.yyyy hh24:mi') diff
FROM t1
ORDER BY abs(diff) asc, SIGN(diff) desc;
C. -
Getting the last set of records based on a Date Field
Hi All
i have the followings data set in a table
TRACK_ID_GRP TRACK_ID_NBR TRACK_SAMPLE_ID START_DATE
970150 129700104071 64260 8/6/2002
970150 229700101893 64261 8/6/2002
970150 149700101893 64262 8/6/2002
970150 97015011 79252 9/19/2005
970150 97015023 79255 9/19/2005
970150 97015013 79253 9/19/2005
970150 97015021 79254 9/19/2005
970040 129900105213 56155 9/26/2000
970040 1101 29841 6/9/1998
970040 97004023 143349 10/28/2008
970040 2101 29842 6/9/1998
970040 97004021 143348 10/28/2008
970040 97004011 143346 10/28/2008
970040 149700101903 64196 7/16/2002
970040 2301 29844 6/9/1998
970040 97004013 143347 10/28/2008
970040 1301 29843 6/9/1998I need to get only those records with the latest date and i'm using the following query
SELECT t.track_id_grp, t.track_id_nbr, t.track_sample_id,
MAX (t.start_date) OVER (PARTITION BY t.track_id_grp) AS start_date
FROM track_table t
WHERE t.track_id_grp IN ('970150', '970040')And i'm getting the following dataset
TRACK_ID_GRP TRACK_ID_NBR TRACK_SAMPLE_ID START_DATE
970040 1.299E+11 56155 10/28/2008
970040 1101 29841 10/28/2008
970040 97004023 143349 10/28/2008
970040 2101 29842 10/28/2008
970040 97004021 143348 10/28/2008
970040 97004011 143346 10/28/2008
970040 1.497E+11 64196 10/28/2008
970040 2301 29844 10/28/2008
970040 97004013 143347 10/28/2008
970040 1301 29843 10/28/2008
970150 1.297E+11 64260 9/19/2005
970150 97015011 79252 9/19/2005
970150 97015021 79254 9/19/2005
970150 2.297E+11 64261 9/19/2005
970150 97015013 79253 9/19/2005
970150 97015023 79255 9/19/2005
970150 149700101903 64262 9/19/2005And i was expecting the following dataset
TRACK_ID_GRP TRACK_ID_NBR TRACK_SAMPLE_ID START_DATE
970150 97015011 79252 9/19/2005
970150 97015023 79255 9/19/2005
970150 97015013 79253 9/19/2005
970150 97015021 79254 9/19/2005
970040 97004023 143349 10/28/2008
970040 97004021 143348 10/28/2008
970040 97004011 143346 10/28/2008
970040 97004013 143347 10/28/2008I was expecting to get only those records with the latest date, instead i'm getting all the records with the max date in it, please need help or advice.
ThanksTry this -
SELECT track_id_grp, track_id_nbr, track_sample_id, start_date
FROM (SELECT t.track_id_grp, t.track_id_nbr, t.track_sample_id,
t.start_date,
ROW_NUMBER () OVER (PARTITION BY t.track_id_grp, t.track_sample_id ORDER BY t.start_date DESC)
AS rn
FROM track_table t
WHERE t.track_id_grp IN ('970150', '970040'))
WHERE rn = 1let me know if that works.
Edited by: Sri on Apr 28, 2011 9:24 AM -
Crystal Report Formula to select Record of only MAX Value
hi Everyone,
i need a simple crystal report formula to select one department whose recived quantity Maximum.
for example:
itemcode dscription departmen op recived issue
1 a ab 2 2 2
1 a bb 0 2 2
1 a bc 4 8 2
1 a cc 2 2 2
i group by item the item show just once but i want a formula to show one department who's recived quantity is maximum.i suppress the detail section.and just show the group footer/
itemcode dscription departmen op recived issue
1 a bc 8 14 8Thanks
Re: Crystal Report Formula to select Record of only MAX Value
Abhilash Kumar -
Selecting records based on user formula
Post Author: Josh@RTA
CA Forum: Formula
I'm writing reports for a company that stores all of their dates as 8 digit numerical fields rather than a date or datetime datatype. I want to convert this field to a date type, then compare it to a parameter that stores user input as a date type.
However, due to the way that Crystal does it's passes over the data, I can't use a selection formula based off of another formula. So I'm wondering , has anyone ever used a selection formula that references another formula and how have you been able to do it? Maybe use group selection instead of record selection? Just not sure.
I'm including the formula I'm using to convert the date, as well as the selection formula so you get an Idea of what I'm doing.
//This converts the numeric 'date' field to a dateshared stringvar DateString := totext({wotrans.ROP_TRAN_DATE}, 0, '');shared datevar ConvertedDate :=If {wotrans.ROP_TRAN_DATE} < 19590101 then Date (1959, 01, 01) else Date ( Val (DateString [1 to 4]), Val (DateString [5 to 6]), Val (DateString [7 to 8]) );
//This is the select statement I'm using to compare the above formula to my parameter using record selection{@ConvertedTransDate} = {?TransDateRange}Post Author: SKodidine
CA Forum: Formula
Replace your formula with this and then equate it to your parameter value in your selection criteria and see if it will work.
If {wotrans.ROP_TRAN_DATE} <= 19590101 then Date (1959, 01, 01)
else
date(
tonumber(totext({wotrans.ROP_TRAN_DATE},0,'','')[1 to 4]),
tonumber(totext({wotrans.ROP_TRAN_DATE},0,'','')[5 to 6]),
tonumber(totext({wotrans.ROP_TRAN_DATE},0,'','')[7 to 8]));
The process might be faster if you convert or change the data type of your parameter to numeric and then compare to the numeric date. -
Select record having most recent date
Table: Order
Code ImportId EntryDate
1 100
10/11/2014
1 101
10/14/2014
1 102
10/10/2014
2 103 10/11/2014
2 104 10/15/2014
I want to select the record having the most recent EntryDate grouped by Code. In the select, i need to return the ImportId.
AnonymousPlease 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. Nothing you posted
was right. Temporal data should use ISO-8601 formats. This is the only format allowed in the ANSI-ISO SQL Standards and it is the most common IT standard on Earth; but you do not know it!
Code should be in Standard SQL as much as possible and not local dialect. There is no such crap as a generic “code” in RDBMS. Table have keys, so you have no table! Rows are not records; this is a basic concept.
This is minimal polite behavior on SQL forums. Here is my guess at what a polite, competent person might have posted.
CREATE TABLE Import_Orders
(order_type INTEGER NOT NULL
CHECK(order_type IN (1,2)),
import_id CHAR(3) NOT NULL PRIMARY KEY,
entry_date DATE NOT NULL);
INSERT INTO Import_Orders
VALUES
(1, 100, '2014-10-11'),
(1, 101, '2014-10-14'),
(1, 102, '2014-10-10'),
(2, 103, '2014-10-11'),
(2, 104, '2014-10-15');
I want to select the record [sic] having the most recent entry_date grouped by order_type. In the select, I need to return the import_id.
If you return only the import_id, then the most recent entry_date does not matter! Think about it! Did you want the whole row with the most recent entry_date? Here is a common idiom.
WITH X (import_id, order_type, entry_date, entry_date_max)
AS
(SELECT import_id, order_type, entry_date,
MAX(entry_date) OVER (PARTITION BY order_type)
FROM Import_Orders)
SELECT import_id, order_type, entry_date
FROM X
WHERE entry_date = entry_date_max;
--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 record according to latest date
I have two fields in my DB table , one is region and other is date .
There are many records for region (R1 lets say).
My requirement is that I want the record (only one record) with the latest date for this region .hi,
try like this.
SELECT - aggregate
Syntax
... { MAX( [DISTINCT] col )
| MIN( [DISTINCT] col )
| AVG( [DISTINCT] col )
| SUM( [DISTINCT] col )
| COUNT( DISTINCT col )
| COUNT( * )
| count(*) } ... .
Effect
As many of the specified column labels as you like can be listed in the SELECT command as arguments of the above aggregate expression. In aggregate expressions, a single value is calculated from the values of multiple rows in a column as follows (note that the addition DISTINCT excludes double values from the calculation):
MAX( [DISTINCT] col ) Determines the maximum value of the value in the column col in the resulting set or in the current group.
MIN( [DISTINCT] col ) Determines the minimum value of the content of the column col in the resulting set or in the current group.
AVG( [DISTINCT] col ) Determines the average value of the content of the column col in the resulting set or in the current group. The data type of the column has to be numerical.
SUM( [DISTINCT] col ) Determines the sum of the content of the column col in the resulting set or in the current group. The data type of the column has to be numerical.
COUNT( DISTINCT col ) Determines the number of different values in the column col in the resulting set or in the current group.
COUNT( * ) (or count(*)) Determines the number of rows in the resulting set or in the current group. No column label is specified in this case.
reward if useful. -
Create a record based on From date and To Date in CRM 2015 Plugins
Hi all
in my account screen i have two date field from date and Todate and i have one child entity member when i am creating a
new account then based on from date and to date number of child record should be created
for example in account screen
if from date=2/1/2015 and
To date=31/03/2015
then number of child record should be created
in this manner
from date to date
2/1/2015 31/01/2015
01/02/2015 28/02/2015
1/03/2015 31/03/2015Hi,
OK. It seems you want to create 3 records (custom child entity) where the first has the same From Date as the Account and goes up to the end of the month, and the other records go from there.
This logic can be implemented via a Plugin that could run on the create and update of these fields on Accounts. From the Plugin, you can set up the logic and fill the records with the necessary information. -
Select records based on first n distinct values of column
I need to write a query in plsql to select records for first 3 distinct values of a single column (below example, ID )and all the rows for next 3 distinct values of the column and so on till the end of count of distinct values of a column.
eg:
ID name age
1 abc 10
1 def 20
2 ghi 10
2 jkl 20
2 mno 60
3 pqr 10
4 rst 10
4 tuv 10
5 vwx 10
6 xyz 10
6 hij 10
7 lmn 10
so on... (till some count)
Result should be
Query 1 should result --->
ID name age
1 abc 10
1 def 20
2 ghi 10
2 jkl 20
2 mno 60
3 pqr 10
query 2 should result -->
4 rst 10
4 tuv 10
5 vwx 10
6 xyz 10
6 hij 10
query 3 should result -->
7 lmn 10
9 .. ..
so on..
How to write a query for this inside a loop.Hi,
So, one group will consist of the lowest id value, the 2nd lowest and the 3rd lowest, reggardless of how many rows are involved. The next group will consist of the 4th lowest id, the 5th lowest and the 6th lowest. To do that, you need to assign numbers 1, 2, 3, 4, 5, 6, ... to the rows in order by id, with all rows having the same id getting the same number, and without skipping any numbers.
That sounds like a job for the analytic DENSE_RANK function:
WITH got_grp_id AS
SELECT id, name, age
, CEIL ( DENSE_RANK () OVER (ORDER BY id)
/ 3
) AS grp_id
FROM table_x
SELECT id, name, age
FROM got_grp_id
WHERE id = 1 -- or whatever number you want
;If you'd care to post CREATE TABLE and INSERT statements for your sample data, then I could test it.
See the forum FAQ {message:id=9360002} -
Select records based on criteria and update those records once read
hi,
I am very new to bpel and DB adapters.
I have a requirement where in I need to query two tables to fetch some records and update these selected records with a new value for field to indicate that bpel has processed these records.
Once I select these I needs the output to be mapped to the output variable.
I am able to select the records based on criteria , but how will i lock these records so that these records do not get processed again. This should be a very simple usecase just that I am not aware.
Thanks,
RobinOnce you have finished reading the records fire an update query , update some field in the table so that it does not get picked up next time.
if you are using polling for picking up the records, then use logical delete scenario, refer....http://docs.oracle.com/cd/E15523_01/integration.1111/e10231/adptr_db.htm#BABEEBIH -
Dynamic Select List based on TextField data
Hi,
I like to dynamically display the select list based on the value in the textfield, the data in the textfield is of character type.
ThanksHello,
Well as you now know HTML based select lists don't work like that, that widget is called a combo box and there will be built in combo boxes in APEX 3.0, it's a fairly complex dhtml widget.
What you might want to do is provide a text item next to your select box and an Add New Value Option in your select list.
Carl -
Can ditto select files based on modification date?
Hi. I'm trying to use ditto to make backups. I would like to have it select only files modified after a certain date. Is there a way to do this?
I noticed the bom (bill of materials) option... can that be used for this purpose somehow? Not quite sure how best to create a BOM that includes only files based on modification date.
Any suggestions? Thanks
Ericditto doesn't provide a way to select only files modified after a certain date -- but find does; see the "-newer" and "-newerXY" options. Using find, you can generate a BOM file listing files that have been modified after a certain date.
Then you can pass that BOM file to ditto.
Powerbook G4 1GHz Mac OS X (10.3.9) -
Selecting records based on formula fields
Post Author: Mike Kennedy
CA Forum: Formula
I have created a field (called "Shortage") that is the result of subtracting two running totals and have inserted all three fields into the group footer. I only want to select those records that have a negative value as a result, but the field is not shown in the Select Expert. None of my formula fields show up in the Select Expert for some reason (normally they do). Does anyone know why and how can I select these records only? Thanks.Post Author: SKodidine
CA Forum: Formula
Running Totals are only available once the records are being read and processed. You are calculating the difference between two Running Totals and then want to use that to select records? I don't think that is possible. One way of accomplishing the display of groups which have a negative value is to use sum functions instead of the running totals and then in group selection criteria, display only those groups which have a negative value as a result of subtracting the two sums.
Maybe you are looking for
-
Can i have multiple paper sizes in one pages document?
Is there any way to configure a pages document with 2 different page sizes? I want to create a 4 page annual report (for online viewing only) where pages 2-3 are shown on a single horizontal 11 x 17 page, but cover and back are 8.5 x 11 vertical.
-
MIR7 exchange rate is not modefied with respect to posting date
Hi Experts, In our SAP system , we use MIR7 to create park invoice at first ,and then use MIR4 to change the parked invoice and post it. but when creating parked invoice, it's in say June and the exchange rate is 100, and when we create real invoice
-
Hi experts please give me solution for how to calculate the cash discount on vendor line items as per the payment term within 30 days 15% cash discount , if we pay the amount before due date(any day from 1 to 30 days) we will receive the cash discou
-
Get ClientContext from Full sharepoint url?
I am receiving a full sharepoint url like 'http://TestServer/sites/TestSite/TestSubSite/_vti_bin/lists.asmx' I know the following code will not work as the url does not directly reference a site. using (var context = new ClientContext(http://TestServ
-
Dear All, we've got a very big problem in oure CRM Mobiles Sales 3.0. In the Out-Queues we've got wrong entries, which have other Queue-ID's than they expecet to have but they've got the same transaction-ID. When the clients now try to make conntrans