473,403 Members | 2,354 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

How to find a record containing latest date?

99 64KB
I have two tables:
1.Students:
Expand|Select|Wrap|Line Numbers
  1. ID  Fist Name   Last Name   Date of Birth
  2. 1   ABC         XYZ         01-04-1999
  3. 2   KLM         NOP         02-06-2001
  4.  
2.Admissions:
Expand|Select|Wrap|Line Numbers
  1. Admission ID    Admission No    Date of Admission    Student ID      Class of Admission
  2. 1               1230            01-04-2011           1               9th
  3. 2               3042            01-05-2011           2               10th
  4. 3               4520            05-09-2011           1               9th
  5.  
I want the result as:

Expand|Select|Wrap|Line Numbers
  1. Student ID  First Name  Last Name  Date of Birth    Admission No  Date of Admission    Class of Admission
  2. 1           ABC         XYZ        01-04-1999       4520          05-09-2011           9th
  3. 2           KLM         NOP        02-06-2001       3042          01-05-2011           10th
  4.  
Please guide me how to design a query. Thanking in advance.
Apr 7 '16 #1
13 3350
NeoPa
32,556 Expert Mod 16PB
Your question isn't very clear. Are you asking for a query that matches each student with the record in the Admissions table that matches their [Student ID] and also has the latest [Date of Admission]?
Apr 7 '16 #2
mshakeelattari
99 64KB
Yes. I need a query. The two tables are linked with the student ID. The latest record from Admissions table is required for each student. Thank you for quick response.
Apr 7 '16 #3
NeoPa
32,556 Expert Mod 16PB
You want something like :
Expand|Select|Wrap|Line Numbers
  1. SELECT   [tS].[Student ID]
  2.        , [tS].[First Name]
  3.        , [tS].[Last Name]
  4.        , [tS].[Date of Birth]
  5.        , [Admissions].[Admission No]
  6.        , [Admissions].[Date of Admission]
  7.        , [Admissions].[Class of Admission]
  8. FROM     [Students] AS [tS]
  9.          INNER JOIN
  10.          [Admissions]
  11.   ON     [tS].[Student ID]=[Admissions].[Student ID]
  12. WHERE    ([Admissions].[Admission ID]=(SELECT [Admissions].[Admission ID]
  13.                                        FROM   [Admissions]
  14.                                        WHERE  ([Admissions].[Student ID]=[tS].[Student ID])
  15.                                          AND  ([Admissions].[Date of Admission]=(SELECT   Max([Admissions].[Date of Admission])
  16.                                                                                  FROM     [Admissions]
  17.                                                                                  WHERE    ([Admissions].[Student ID]=[tS].[Student ID])
  18.                                                                                  GROUP BY [Admission ID]))))
  19. ORDER BY [Student ID]
  1. The innermost sub-query gets the maximum date for the student.
  2. The next level in gets the [Admission ID] that matches both the date and the [Student ID].
  3. The outer query drops any matched records between the two tables that don't match the correct [Admission ID] returned by the query from #2 above.
Apr 7 '16 #4
mshakeelattari
99 64KB
Showing Syntax Error in query expression SELECT [Admissions].[AdmissionID]
FROM [Admissions]
WHERE ([Admissions].[StudentID]=[tS].[ID])
AND ([Admissions].[DateofAdmission]=(SELECT Max([Admissions].[DateofAdmission]
FROM [Admissions].[DateofAdmission]
WHERE ([Admissions].[StudentID]=[tS].[ID])
GROUP BY [Admissions].[AdmissionID]))))


and when I removed a parenthesis from end and put one after Max([Admissions].[DateofAdmission], then the error message was replaced by: Could not find file 'C:\Users\xxx\Documents\Admissions.mdb'
Apr 7 '16 #5
mshakeelattari
99 64KB
Please note that I am using ms access 2016
Apr 7 '16 #6
NeoPa
32,556 Expert Mod 16PB
mshakeelattari:
and when I removed a parenthesis from end and put one after Max([Admissions].[DateofAdmission], then the error message was replaced by: Could not find file 'C:\Users\xxx\Documents\Admissions.mdb'
You're right to make those changes. I would expect them to work, all else being equal.

From the error message I would guess that all isn't as I posted. My first guess is that the name of your table is different from what you've posted. I notice that in your first post you say there is a field called [Date of Admission], yet your error message refers to it as [DateofAdmission]. SQL isn't human. It requires everything to be exactly as they are in the database. Humans may recognise what you're referring to is 'the same', but SQL doesn't. It requires precision.

If this still persists after you've looked at the SQL again and tidied up anything that needs to be, then post your actual SQL and the exact error message and I'll see what I can do to find the error for you.

Error messages can be captured as pictures using Ctrl-C, even when it's not possible to select the actual text and copy that. Feel free to post an attached picture with the error message on if that's necessary.

PS. I'm going to change the original post now (#4) so that anyone else reading it gets the correct SQL and doesn't get confused by the errors.
Apr 7 '16 #7
mshakeelattari
99 64KB
I am really sorry for these minor differences that I posted in my first post, however, I modified the fields names according to my actual field names as are in my database. In my table "Students", the primary key field is "ID" only while in table "Admissions", the field name is "StudentID". Secondly, I have used no spaces in the names of the fields in "Admissions" table. Keeping these things in view, I am posting the SQL statement and the snapshot of the error message here.

Attached Images
File Type: jpg Untitled.jpg (58.7 KB, 603 views)
Apr 8 '16 #8
mshakeelattari
99 64KB
I made a modification in the code provided by you and the problem vanished. However another problem appeared.

Expand|Select|Wrap|Line Numbers
  1. SELECT 
  2.         tS.ID, tS.[Urdu Name],
  3.         tS.[English Name],
  4.         tS.[Date of Birth],
  5.         Admissions.AdmissionNo,
  6.         Admissions.DateofAdmission
  7. FROM Students AS tS 
  8. INNER JOIN Admissions 
  9. ON tS.[ID] = Admissions.[StudentID]
  10. WHERE (((Admissions.AdmissionID)=(SELECT [Admissions].[AdmissionID]
  11.                                            FROM   [Admissions]
  12.                                            WHERE  ([Admissions].[StudentID]=[tS].[ID])
  13.                                              AND  ([Admissions].[DateofAdmission]=(SELECT   Max([Admissions].[DateofAdmission])
  14.                                                                                      FROM     [Admissions].[DateofAdmission]
  15.                                                                                      WHERE    ([Admissions].[StudentID]=[tS].[ID])
  16.                                                                                      GROUP BY [Admissions].[AdmissionID])))))
  17. ORDER BY Admissions.[StudentID];
I Deleted the underlined word:
Expand|Select|Wrap|Line Numbers
  1. From [Admissions].[DateOfAdmission]
in the innermost subquery.
However, a new message now appears: "At most one record can be returned by this subquery" when I run this query.
Apr 8 '16 #9
mshakeelattari
99 64KB
And at last I succeeded with the grace of my Lord Allah. I created my own query and that was successful. It is:
Expand|Select|Wrap|Line Numbers
  1.  
  2. SELECT
  3.      Students.ID,
  4.      Students.[Urdu Name],
  5.      Students.[English Name],
  6.      Students.[Date of Birth],
  7.      MyQuery2.AdmissionNo,
  8.      MyQuery2.DateOfAdmission
  9.   FROM
  10.      (SELECT Admissions.AdmissionID,
  11.              Admissions.AdmissionNo, 
  12.              Admissions.StudentID,
  13.              Admissions.DateOfAdmission
  14.            FROM
  15.               (SELECT Admissions.StudentID,
  16.                       Max(Admissions.DateOfAdmission)
  17.                           AS MaxOfDateOfAdmission
  18.                   FROM Admissions
  19.                   GROUP BY Admissions.StudentID)
  20.                       AS MyQuery
  21.                INNER JOIN
  22.                           Admissions
  23.                ON
  24.                           MyQuery.StudentID = Admissions.StudentID
  25.                WHERE (((Admissions.DateOfAdmission)=[MyQuery].[MaxOfDateOfAdmission]))
  26.                           ORDER BY Admissions.StudentID)
  27.                    AS MyQuery2
  28.                         INNER JOIN
  29.                                   Students
  30.                         ON
  31.                                   MyQuery2.StudentID = Students.ID
  32.                         ORDER BY Students.ID
  33.  
  34.  
However I am grateful to you also as your help showed me the way. Thank you very much.
Apr 8 '16 #10
NeoPa
32,556 Expert Mod 16PB
I'm happy for you that you've managed to find a solution. You should understand, though, that SQL of such complexity when displayed with no formatting like that, is very difficult to read and understand.

You definitely found another problem with my SQL, which I've fixed again in the original. It's very unfortunate to have been working with information that changed from post to post. As that's all I have to work with if it's not reliable then trying to get something to work - especially without having something to test it on myself - is always going to be very difficult.

You've learned something anyway. And that's no small feat. There aren't too many that can take that idea and make it work independently as you have. Well done for that. Hopefully, you've also learned the importance of starting with the right information in the question. That will save you a lot of time and effort in future.
Apr 8 '16 #11
mshakeelattari
99 64KB
I again apologize for changing information. I have formatted the SQL. Please check it for any deficiency and suggest any improvement.
Apr 8 '16 #12
NeoPa
32,556 Expert Mod 16PB
mshakeelattari:
I again apologize for changing information.
I hear you. My comment wasn't intended to make you feel bad or to criticise. It was simply to hope that you've lerned from this time. I suspect you have as you seem to learn fast. Anyway, here's my latest response. Again, not being able to do a good job formatting SQL isn't a criticism. It will help you if you learn how to, but if you do you'll be one of a very small number that can.

I guess that (Reformatting the SQL) is not as easy to do as I'd imagined. The main point is to keep items which are at the same level logically, at the same indentation too. Notice in my SQL below that everything that is offset by one character is because it's contained within parentheses. Clause names like SELECT, FROM, GROUP BY, WHERE, etc. for the same query, are all in the same column.

Anyway, I moved your SQL around to make it more readable and noticed that it used a completely different approach from my suggestion. Where I used a sub-query as a filter, you used it to JOIN to the other data. Your approach should work equally as well as mine.

Your approach even has scope for losing one level of sub-query :
Expand|Select|Wrap|Line Numbers
  1. SELECT   [Students].[ID]
  2.        , [Students].[Urdu Name]
  3.        , [Students].[English Name]
  4.        , [Students].[Date of Birth]
  5.        , [MyQuery].[AdmissionNo]
  6.        , [MyQuery].[DateOfAdmission]
  7. FROM     ([Students]
  8.           INNER JOIN
  9.           [Admissions]
  10.   ON      [Students].[ID]=[Admissions].[StudentID])
  11.          INNER JOIN
  12.          (SELECT   [Admissions].[StudentID]
  13.                  , Max([Admissions].[DateOfAdmission]) AS [MaxOfDateOfAdmission]
  14.           FROM     [Admissions]
  15.           GROUP BY [Admissions].[StudentID]
  16.           ORDER BY [Admissions].[StudentID]) AS [MyQuery]
  17.   ON     [Students].[ID]=[MyQuery].[StudentID]
  18. WHERE    ([Admissions].[DateOfAdmission]=[MyQuery].[MaxOfDateOfAdmission])
  19. ORDER BY [Students].[ID]
If I'm honest, I think your approach was a better one than mine. If I were to guess, I'd say that you have a good future in database work. Good luck.
Apr 9 '16 #13
mshakeelattari
99 64KB
Lot of thanks for you!
Apr 10 '16 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: jas | last post by:
> This is what I want to do with the data table below. > > I only want it to show one id for each issue. ( ie, 4001 only once, > 4002 only once, etc. But only the one with the latest date and...
3
by: MostlyH2O | last post by:
Hi Folks, I have a query that joins 3 tables. One of the tables (SalaryData) has data where there may be duplicate records with different dates. Of those duplicate records, I want the query to...
8
by: TGEAR | last post by:
I have an ItemSTDPriceHistory table as below and this is a child table of itemlookup table with one to many relationship. if exists (select * from dbo.sysobjects where id = object_id(N'.') and...
20
by: keri | last post by:
Hi, I am creating a table where I want to use the date as the primary key - and to automatically create a record for each working date (eg Mon to Fri) until 30 June 2007. Is this possible? I do...
6
by: piyushdabomb | last post by:
Hi All, Currently, I have a SQL query where I need to grab the SECOND latest date by group. COMPONENTID COMPLETIONDATE CBT_HAZCOM 02/26/2007 15:17:00 CBT_HAZCOM 07/31/2007 21:23:00 QS ...
4
by: ringer | last post by:
I have a db where each record is a certain task to be done. Each record includes the date the task should be completed. Some of the tasks are one time only but some are recurring. I have been having...
8
by: helpmeplease213 | last post by:
Hello, I have a table that has five categories: Unit No, Date, P1, P2, P3. I have a query that only extracts data from the table that is over 40 for P1, P2 or P3 but I only want the data with...
2
by: selvialagar | last post by:
i have a date field in a table..i want to retrieve the data with latest date...is there any query for that.....
1
by: SunshineInTheRain | last post by:
I have a log table. I want to get record of latest date. Meaning if 1-May-2008 13:32:22 and 1-May-2008 2:22:21, it will retrieve 1-May-2008 13:32:22 as a result. how the statement should be? ...
4
by: BlackEyedPea | last post by:
Hi there, I have a table, which has an order number, a comment & a date the comment was added. Therefore you could have 3 or 4 comments against one order number. All I want to do is create a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.