This question already has an answer here:
Filter query result by most recent date
(1 answer)
Closed 8 years ago.
Here's the table below I am using in MS-Access.
There can be multiple entries for the same item but I need to get the value corresponding to the latest dated entry. For example considering the below dataset,
If I want to know what the closingStock for item 'XYZ' is, it should return 70 as that is the latest entry (as per date /dd-mm-yyyy). I am using ms-access and vb.net for this, which I am very much unfamiliar with and have tried using a max(date) etc, but access syntax/interface seems a bit weird to me now. Would appreciate any help. I would prefer to do this in vb.net code.
Try this:
SELECT Max(tblInventory.transdate) AS MaxOftransdate, tblInventory.item, Last(tblInventory.closingStock) AS LastOfclosingStock
FROM tblInventory
GROUP BY tblInventory.item;
Replace the tblInventory with whatever your table name is. You can also replace the 'Max' with 'Last' if you prefer
Craig
Related
This question already has answers here:
Add days Oracle SQL
(6 answers)
Closed 12 months ago.
I am having an issue trying to add a portion to my WHERE clause to get only the last 3 days of data rather than grab the whole table. The date format comes through as 'dd-Mon-yy'
Here is my current WHERE clause
WHERE ("IAINVN00"."REF_LOCN" LIKE '51C%'
OR "IAINVN00"."REF_LOCN" LIKE '511%')
This works fine, just brings back way too much data. When I add:
and "IAINVN00"."ADJDATE" >= (Date()-3)
This brings back an error of "ODBC--call failed. [Oracle][ODBC][Ora]ORA-00936: missing expression (#936)"
I have tried using this as well and get the same error
DateAdd("d",-3,Date())
In order to fix this, instead of using Date, I needed to use SysDate.
and "IAINVN00"."ADJDATE" >= sysdate - 3
I'm working on a query that pulls a date from another query, I have my reasons for the nesting. The problem I'm facing is that there is a field that is called DueDate.
My SQL is
SELECT DueDate
FROM qryDueDates
WHERE DueDates <= DateAdd("d",60,Date())
The data causing the issue is when it equals something like "1/25/2019", "11/19/2019" or any date in 2019.
Goal
I need to limit the results to show dates that are expired or expiring within 60 days or less.
I'm trying to prepare the dataset for the conditional formatting.
if you can put your nested sub-query in your post that may give better picture, and if you can mention what is the error you are getting that may also help. Since you mentioned that you are getting error only when sub-query returns certain dates, I would suggest that cast your sub-query result to DATE if you have not already done.
Below is my attempt to help you with limited information I could extract from your post. I have used some of MS-SQL function below, please replace with your DB specific function.
SELECT myDates.* FROM (select COLUMN_NAME DueDates from TABLE_NAME) as myDates WHERE myDates.DueDates <= DateAdd("d",60, GETDATE())
Turns out that the original query was screwing it up. I moved the query into the main one and it worked.
My question is how to properly write a SQL query for the below highlighted/bold question.
There is a table in HMO database which stores doctor's working
hours.Table has following fields
"FirstName","LastName","Date","HoursWorked". write a sql statement
which retrieves average working hours for period January-March for a
doctor with name Joe Doe.
so far i have
SELECT HoursWorked
FROM Table
WHERE DATE = (January - March) AND
SELECT AVG(HoursWorked) FROM Table WHERE FirstName="Joe",LastName="Doe"*
A few pointers as this sounds like a homework question (which we don't answer for you here, but we can try to give you some guidance).
You want to put all the things you want to return from your select first and you want to have all your search conditions at the end.
So the general format would be :
SELECT Column1,
Column2,
Column3,
FROM YourTable
WHERE Column4 = Restriction1
AND Column5 = Restriction2
The next thing you need to think about is how the dates are formatted in your database table. Hopefully they're kept in a column of type datetime or date (options will depend on the database engine you're using, eg, Microsoft SQL Server, Oracle or MySql). In reality some older databases people use can store dates in all sorts of formats which makes this much harder, but since I'm assuming it's a homework type question, lets assume it's a datetime format.
You specify restrictions by comparing columns to a value, so if you wanted all rows where the date was after midnight on the 2nd of March 2012, you would have the WHERE clause :
WHERE MyDateColumn >= '2012-03-02 00:00:00'
Note that to avoid confusion, we usually try to format dates as "Year-Month-Day Hour:Minute:Second". This is because in different countries, dates are often written in different formats and this is considered a Universal format which is understood (by computers at least) everywhere.
So you would want to combine a couple of these comparisons in your WHERE, one for dates AFTER a certain date in time AND one for dates before another point in time.
If you give this a go and see where you get to, update your question with your progress and someone will be able to help get it finished if you have problems.
If you don't have access to an actual database and need to experiment with syntax, try this site : http://sqlfiddle.com/
you already have the answer written
SELECT AVG(HoursWorked) FROM Table WHERE FirstName="Joe",LastName="Doe"*
you only need to fix the query
SELECT AVG(HoursWorked) as AVGWORKED FROM Table WHERE FirstName='Joe' AND LastName='Doe'
That query will give you the average hours worked for Joe Doe, however you only need to get between some time you add the next "AND", if you are using SQL server you can use the built in function DateFromParts(year,month,day) to create a new Date, or if you are using another Database Engine you can convert a string to a DateColumn Convert(Date,'MM/dd/yyyy')
Example
SELECT AVG(HoursWorked) as AVGWORKED FROM Table WHERE FirstName='Joe' AND LastName='Doe' AND DateColumn between DateFromParts(year,month,day) and Convert(Date,'MM/dd/yyyy')
In the example i showed both approaches (datefromparts for the initial date, and convert(date) for the ending date).
I recently discovered an old Microsoft Access database I made for recording a list of books and ticking off which ones I've read and in what year.
At the moment, this includes a BOOKS table which has a column for 'Read' and 'Year'. The query which generates the table of results gets the year column and counts how many books were read in each year, e.g:
2010: 8
2011: 10
2012: 20
However, this means that if no books are marked as read in, for example, 2015, then 2015 is just left out of the chart completely. Ideally it would show up with a value of 0.
Is there any way of doing this? I don't mind delving into the SQL itself. So far my initial thoughts are working out the number of years from 2010 to current year (using DateDiff), and somehow iterating over those years to count the number of books read... but I don't know if that's possible in SQL.
Create a numbers table with one row for each year in your target year range. Then LEFT JOIN that table to BOOKS and do your counting ...
SELECT n.the_number, Nz(Count(b.Year), 0) AS books_read
FROM
numbers AS n
LEFT JOIN BOOKS AS b
ON n.the_number = b.Year
WHERE n.the_number BETWEEN 2010 AND Year(Date())
GROUP BY n.the_number;
Note you would not need the WHERE clause if your numbers table contains only the years you're interested in. However a numbers table can be useful in other situations where you might want a different range of numbers. So a similar WHERE clause will allow you to target a specific subset of the numbers contained in the table.
I have two database in SQL Server. I wanted to find out the data older than (let say 3) years.
I know the database creation date, currently I have around 550 GB (both the database) of data spanned for 7 years, I wanted to know 'how much of the DB data (out of total 550 GB)is older than 3 years OR (5 years)'?
I was going through this link but couldn't get the expected data.
SQL SERVER – Query to find number Rows, Columns, ByteSize for each table in the current database – Find Biggest Table in Database
One of the solution coming in my mind right now is to find out the total number of rows accounted for 7 years (easily get this number), total number of rows accounted for 5 years (starting from the date creation) (don't know how to get this number).
then for row_count_7_years accounts for 550 GB of data , what will be the row_count_5_years? i will get the approx data.
Please Help
For such purposes you should keep some datetime field as marc mentioned. I suppose you don't have it.
In you suggested solution you can get the whole count of rows from your table (for 7 years i suppose), but you wouldn't be able to get the rows for 5 years, because there is no date.
You can get the whole number of records for 7 years and divide them on the number of years, and ONLY IN CASE you have your database avarage fulfill, you can make query for top (numberOFRows in one year)*5 and order them by row_number(). The result - the rows, you should delete. But I wouldn't recommend you to use this solution.
I would recommend you to alter your tables and add the datetime columns for each of them. Before that you should make the backup for the whole date and copy it somewhere. After 3 years you would be able to make your clean up.
as mentioned above u shud have a date column , however if you dont , depending on the realtionships in your tables u might be able to estimate the number of rows looking up realtionships with some other table that has the datetime column , else if you have a backup ( unlikely but still) you can restore that to identify the delta