I am stuck with something. I am trying to take a long column of dates of which are formated to show also hours and minutes and run a Group query to paste values at the date level without acknowledging the differences in hours and minutes.. Unfortunately I have no clue how to start. The code i put together so far which returns each grouped date with the hour and minutes is as follows:
st_sql = "INSERT INTO [tblSearchEngine03] ([Date])" & _
"SELECT [tblSearchEngine02].[Date]" & _
"FROM [tblSearchEngine02]" & _
"GROUP BY [tblSearchEngine02].[Date]" & _
"ORDER BY [tblSearchEngine02].[Date]"
Application.DoCmd.RunSQL (st_sql)
Im not sure the best way to truncate the date on table "tblSearchEngine02"..
Focus on the SELECT piece first. You can use DateValue() for your Date field values. Start with this as a new query in the Access query designer:
SELECT DateValue(se02.Date)
FROM tblSearchEngine02 AS se02
GROUP BY se02.Date
ORDER BY se02.Date
Or you could use DISTINCT instead of GROUP BY:
SELECT DISTINCT DateValue(se02.Date)
FROM tblSearchEngine02 AS se02
ORDER BY se02.Date
After you have the SELECT working correctly, you can convert it to an INSERT query (the Access query designer calls it an "append" query).
And when you later build the same statement in your VBA code, include Debug.Print st_sql so that you can view the completed statement text in the Immediate window and make sure it is what you expected. (You can use Ctrl+g to go to the Immediate window.)
One way of doing this is to format the date/time as a date string. If you use YYYY/MM/DD it will sort properly. Otherwise you can convert the date/time to an int to trim off the time and then convert back to a date/time type.
Here is an example of formatting as string:
Format([tblSearchEngine02].[Date], "yyyy/mm/dd")
Here is an exmple of converting to get to a date (the end result will be a date/time data type so it might render as 03/16/2014 00:00 depending on your locale info)
CDate(CInt([tblSearchEngine02].[Date]))
Access stores its dates as floating point numbers where the integer part is the number of days since Jan 1, 1900 and the fractional part is the fraction of the day (time of day). Access is quite happy to treat these dates as numbers without doing any conversions, so:
fix([tblSearchEngine02].[Date])
will trim the fractional part of the day and set the time back to midnight and allow you to group by day.
Related
I have an SQL query in access that will grab all records where a calculated date is in between two values. It works fine if I hardcode date literals such as:
SELECT *
FROM Table
WHERE DateAdd("d",-60,DateAdd("yyyy",65,[Table].[BirthDate])) Between #3/21/2021# And #3/27/2021#;
However I need to parametrize the the between dates so that they can be entered by a user like:
SELECT *
FROM Table
WHERE DateAdd("d",-60,DateAdd("yyyy",65,[Table].[BirthDate])) Between [StartDate] And [EndDate];
However when I run the latter query and enter the exact same dates as the former, hard-coded one, it starts pulling records outside the between range. I've attempted to enter the dates like 3/21/2021 as well as date literals like #3/21/2021# and neither work. The latter doesn't pull anything at all.
I also have a form with a handful of text boxes using the short date format that let the user pick the dates for the query. It has the same issue of pulling back incorrect records. None of the records have any time component to my knowledge.
How can I get the date between to correctly work with user entered parameters?
Access doesn't know what data type your parameters are, so specify that in the query:
PARAMETERS
StartDate DateTime,
EndDate DateTime;
SELECT
*
FROM
Table
WHERE
DateAdd("d",-60,DateAdd("yyyy",65,[Table].[BirthDate])) Between [StartDate] And [EndDate];
Parameters worked to filter a native field - not the calculated date. However, using CDate() function worked.
SELECT *
FROM Table
WHERE DateAdd("d",-60,DateAdd("yyyy",65,[Table].[BirthDate]))
Between CDate([StartDate]) And CDate([EndDate]);
But before I remembered that, I tested calculating with inputs back to a birthdate range which also worked.
SELECT *
FROM Table
WHERE [BirthDate] Between DateAdd("d",60,DateAdd("yyyy",-65,[StartDate]))
And DateAdd("d",60,DateAdd("yyyy",-65,[EndDate]));
I'm trying to make a query with SQL Server Management Studio 2017 that brings back a count of all the servers with a projected migration date of this year. I have one query made now, but it's still bringing back some servers with dates from years before.
SELECT MONTH(Projected) as [Month], count(*) as [Total]
FROM dbo.tFake
WHERE Projected >='01/01/2019' AND Projected <='12/31/2019
GROUP BY Month(Projected)
ORDER BY [Month]
Date format is mm/dd/yyyy btw. How can I get this query to bring back just servers that are projected for the year 2019?
Going by the assumption that your data type is wrong, the first step is to fix that.
Note, I am assuming that your data only contains dates, and not time (which your query implies). Firstly, you'll need to change the value of all your rows to an convertible value, we'll go with the ISO format yyyyMMdd:
UPDATE dbo.tFake
SET Projected = CONVERT(varchar(8),CONVERT(date,Projected,101),112);
Now that all the rows are a literal string in the format yyyyMMdd we can alter the column:
ALTER TABLE dbo.tFake ALTER COLUMN Projected date;
Now, we can run your query again, but now your data type is correct, you won't have the problem:
SELECT MONTH(Projected) as [Month], count(*) as [Total]
FROM dbo.tFake
WHERE Projected >= '20190101' AND Project < '20200101' --I prefer the >= and < method. This is especially import with date & time data types
GROUP BY Month(Projected)
ORDER BY [Month];
Notice the literal strings I passed are also in the yyyyMMdd format. If you must pass a literal string in the format MMddyyyy you can wrap in a CONVERT with the style code 101: CONVERT(date,'12/31/2019',101). 101 means the US style date (CAST and CONVERT (Transact-SQL).
Remember, this solution assumes you have date only values, and not date and time values. If you do (have date and time values) you'll want to use an appropriate date and time data type and use the ISO8601 style, instead of the ISO style.
I am writing a SQL query for MS Access.
The two fields are DateTime. The start/end time are 22:30/6:30
When I run the following query
SELECT cDate(Format(table1.BeginTime,"hh:mm")),
I get 10:30 PM instead of 22:30. I do not want to convert to 12hrs format. How do I keep the Miliary time format?
So I tried a few things in Access 2013 and it seems that #Bjones has a point.
In SQL Server Format is a clr .net function and format(date, 'hh:mm') will be 12 hour and Format(date, 'HH:mm') will be 24 hour.
But as #Bjones pointed out there may be some question of how your original column is held as text or date or time..... And what I have concluded after trying is that your order of functions is wrong.
cDate(Format(table1.BeginTime,"HH:mm"))
cDate transforms the content to a date but it doesn't format it.
So
FORMAT(cDate(table1.BeginTime), "hh:mm")
or
FORMAT(cDate(table1.BeginTime), "HH:mm")
or
FORMAT(cDate(table1.BeginTime), "Short Time")
should give you what you want if the time is stored as text. If stored as date time you can just drop the cDate all together and stay with
FORMAT(table1.BeginTime, "Short Time")
as #Bjones answered.
You don't tell what the result of the query is intended for.
If you need the date value and to view this in 24 hour format, use:
Select table1.BeginTime
and apply a Format property for the column of h:nn or hh:nn
If you need the date formatted as a string in 24 hour format, use:
Select Format(table1.BeginTime, "hh:nn")
and no Format is needed.
In any case, even though the format string h:mm will work, do use h:nn or hh:nn, as m is for the month.
I think what you need to get rid of is the cDate function as your fields are already in DateTime format.
SELECT Format(table1.BeginTime,"hh:nn")
I have the following code:
"SELECT top 1 * FROM CensusFacility_Records WHERE Division_Program = 'Division 1' AND JMS_UpdateDateTime = '" & date & "'"
The date format in column JMS_UpdateDateTime is:
8/22/2013 12:00:07 AM
How can I make sure that my "date" in the query is converted to the correct time format?
My date variable in my SQL query is a real/date time. I would like for it to match the format within the JMS_UpdateDateTime field.
If your database table is small enough, you can cast the value to an actual datetime inside your query, and pass the value in as a datetime parameter, so you're comparing dates instead of comparing strings.
If your table has a decent amount of records, don't do this, because it will be a performance hog.
SELECT top 1 *
FROM CensusFacility_Records
WHERE Division_Program = 'Division 1'
AND cast(JMS_UpdateDateTime as datetime) = #dateParam
I believe SQL Server will be able to read the string that's in your database and automatically cast it properly, assuming your server settings are standard.
But in any case, use parameterized SQL instead of passing in a string like you've got.
The format of your SQL DateTime is actually a bit of a red herring here - it can be displayed in any way the front end (e.g. Management Studio) chooses. The important thing here is that your date variable is in an unambiguous format. With this in mind I'd recommend using the ISO 8601 date/time format, e.g. date.ToString("o") (assuming date is a DateTime).
I've been tasked to take a calendar date range value from a form front-end and use it to, among other things, feed a query in a Teradata table that does not have a datetime column. Instead the date is aggregated from two varchar columns: one for year (CY = current year, LY = last year, LY-1, etc), and one for the date with format MonDD (like Jan13, Dec08, etc).
I'm using Coldfusion for the form and result page, so I have the ability to dynamically create the query, but I can't think of a good way to do it for all possible cases. Any ideas? Even year differences aside, I can't think of anything outside of a direct comparison on each day in the range with a potential ton of separate OR statements in the query. I'm light on SQL knowledge - maybe there's a better way to script it in the SQL itself using some sort of conversion on the two varchar columns to form an actual date range where date comparisons could then be made?
Here is some SQL that will take the VARCHAR date value and perform some basic manipulations on it to get you started:
SELECT CAST(CAST('Jan18'||TRIM(EXTRACT(YEAR FROM CURRENT_DATE)) AS CHAR(9)) AS DATE FORMAT 'MMMDDYYYY') AS BaseDate_
, CASE WHEN Col1 = 'CY'
THEN BaseDate_
WHEN Col1 = 'LY'
THEN ADD_MONTHS(BaseDate_, -12)
WHEN Col1 = 'LY-1'
THEN ADD_MONTHS(BaseDate_, -24)
ELSE BaseDate_
END AS DateModified_
FROM {MyDB}.{MyTable};
The EXTRACT() function allows you to take apart a DATE, TIME, or TIMESTAMP value.
You have you use TRIM() around the EXTRACT to get rid of the whitespace that is added converting the DATEPART to a CHAR data type. Teradata is funny with dates and often requires a double CAST() to get things sorted out.
The CASE statement simply takes the encoded values you suggested will be used and uses the ADD_MONTHS() function to manipulate the date. Dates are INTEGER in Teradata so you can also add INTEGER values to them to move the date by a whole day. Unlike Oracle, you can't add fractional values to manipulate the TIME portion of a TIMESTAMP. DATE != TIMESTAMP in Teradata.
Rob gave you an sql approach. Alternatively you can use ColdFusion to generate values for the columns you have. Something like this might work.
sampleDate = CreateDate(2010,4,12); // this simulates user input
if (year(sampleDate) is year(now())
col1Value = 'CY';
else if (year(now()) - year(sampleDate) is 1)
col1Value = 'LY'
else
col1Value = 'LY-' & DateDiff("yyyy", sampleDate, now());
col2Value = DateFormat(sampleDate, 'mmmdd');
Then you send col1Value and col2Value to your query as parameters.