I have a datatable with 2 columns: "amount" and "date"
I want to sum "amount" by month & year.
I am trying this:
_tAmount = myDT.Compute("sum(amount)", "date LIKE '%/" & i & "/" & _year & "'")
where:
var i equals a nº month ( 1 to 12)
var _year equals nº year (example:
2011)
But not displays any results....How I can do it? What is wrong?
I am working with the spanish format (example day/month/year). But I have tried with the english format (month/day/year) and no results too.
This is on VB.NET 2008.
I don't thing date works with LIJKE, why don't you use:
dim startdt as date = new date(_year, month, 1)
dim enddt as date = startdt.addmonth(1).adddays(-1)
_tAmount = myDT.Compute("sum(amount)", "date >= " & startdt & " AND date <= " & enddt)
This is out the top of my head, so check it yourself, but you should get the idea.
Also, I use mostly the # sign around the dates to force english notation, but you'll have to experiment yourself.
Related
I have a set of data that includes a field called ReleaseDate, type of Date/Time, that gets written using NOW() at the time a record is added.
I can open the table and filter for today's date and get a result of 152 records.
I can run this following query, enter today's date at the prompts, and also get a result of 152 records.
SELECT ProductData.ReleaseDate, ProductData.Shift, ProductData.ExtrusionLine, ProductData.RollDensity
FROM ProductData
WHERE (((ProductData.ReleaseDate) Between [Please Enter Start Date mm/dd/yyyy] & " " & #12/30/1899# And [Please Enter End Date mm/dd/yyyy] & " " & #12/30/1899 23:59:59#));
If I run the following query no records are retrieved. I cannot figure out why.
SELECT ProductData.ReleaseDate, ProductData.Shift, ProductData.ExtrusionLine, ProductData.RollDensity
FROM ProductData
WHERE (((ProductData.ReleaseDate)=Date()));
From what I have read Date() as a criteria should return any records with today's date. Prompting for the date is not an option.
In addition to Gutav's answer, better use:
WHERE ProductData.ReleaseDate >= Date() AND ProductData.ReleaseDate < DateAdd("d", 1, Date())
as this can use an index on ProductData.ReleaseDate (faster). See my answer on Unable to use today's date as a criteria in a query
It's because ReleaseDate contains a time part (from Now()). You can strip that:
WHERE Fix(ProductData.ReleaseDate) = Date();
I want to check if a variable date is in the month that is two months prior to today's date.
Is there a way (using a built in date funciton like dateadd()) to cover the edge cases of when month(now())=1 or month(now())=2 in more elegant manner than the following?
?format(month(now()) & " " & year(now()),"MMMM YYYY")=format(dateadd("M",2,format(varMonth & " " & varYear, "MMMM YYYY")),"MMMM YYYY")
You can use the DateDiff function with the "m" interval to calculate the difference in months between two dates.
I have searched for a solution to my issue for quite some time, but cannot seem to find an answer that works. I have a table that contains influx of cases to the different lawyers based on date and casetype. Keep in mind that I'm a rookie when it comes to VBA and SQL
What I'm trying to do:
I need to sort the massive amount of cases into how many cases each lawyer gets based on dates, which in this case is recurring last month. Essentially I need to be able to press a button every month and then the data for the previous month is automatically retrieved and placed in an excel workbook. All of this has actually succeeded, except for the following problem
Problem:
Whenever I run the macro it doesn't retrieve the full amount. For instance, in February I know there were 159 new cases, but the formula only finds 155. Now I can get the correct result, by prompting an inputbox for a startdate and enddate and entering the format DD/MM/YY HH/MM/SS - But I would like to remove the inputbox part, so I don't have to type anything. The code should automatically take the last month in its enterity. For Feb. it would look like from 01/02/18 00:00:01 to 28/02/18 23:59:59
I assume the problem is because my current formula, doesn't extend all way and therefore excludes the hours, minutes and seconds - or something similar.
I am also pretty confident it can be fixed with the dateadd function, I just don't know how. How do you specify a Startdate and Enddate to include the entire month, down to the very first and last second?
Might be a very easy fix, but it's beyond me
Code:
Dim Startdate As Date
Dim Enddate As Date
Startdate = DateSerial(Year(Now), Month(Now) - 1, 1)
Enddate = DateSerial(Year(Now), Month(Now), 0)
Debug.Print Startdate, Enddate
Set rs = conn.Execute("Select [Jurist], [OpretDato], [Tilgang] From [dbo].[TilgangOgAfgangAfSagerTilgangIPeriodenView]" & _
"Where [OpretDato] Between '" & Startdate & "' And '" & Enddate & "' and (Jurist not in ('BF','MLT','NL') or Jurist is null)" & _
"Order by [Jurist] ASC ;")
Your four records are probably missing from the last day, because 2018-02-28 = 2018-02-28 00:00:00 = midnight at the beginning of February 28th.
Another problem with your formula: think what will happen in January 2019... Your formula (and others answers here) will return:
Year = 2019 Month = 0 Day = 1
Obviously, that won't work. You can't just "subtract 1 from the month" to consistently get a previous month.
Also, you shouldn't specify a end time of 23:59:59 and start time of 00:00:01, since you're skipping over 12 minutes a year ...as well as the month of December.
This is the correct way to handle "previous month" criteria:
EndDate = DateSerial(Year(Now), Month(Now), 1)
StartDate = DateSerial(Year(EndDate - 1), Month(EndDate - 1), 1)
and then your SQL criteria would be:
WHERE ([RecordDateTime] >= StartDate And [RecordDateTime] < EndDate)
Note that the = is NOT included in the second half of the criteria.
Your adjusted code:
Set rs = conn.Execute("Select [Jurist], [OpretDato], [Tilgang] " & _
"From [dbo].[TilgangOgAfgangAfSagerTilgangIPeriodenView]" & _
"Where [OpretDato] >= '" & Startdate & "' And [OpretDato] < '" & _
Enddate & "' and (Jurist not in ('BF','MLT','NL') or Jurist is null)" & _
"Order by [Jurist] ASC ;")
Alternatively, use DateAdd() which follows in line with #ashleedawg's point of using the strictly less, <, than on the current month for EndDate (consistent across any year/month). Additionally, below uses a ADO parameterization to separate SQL code from VBA data and not string interpolation (an industry best practice).
Dim StartDate As Date, EndDate As Date
Dim strSQL As String
EndDate = DateAdd("d", -Day(Date) + 1, Date)
StartDate = DateAdd("m", -1, EndDate)
Debug.Print StartDate, EndDate
' PREPARED STATEMENT
strSQL = "SELECT [Jurist], [OpretDato], [Tilgang] " & _
" FROM [dbo].[TilgangOgAfgangAfSagerTilgangIPeriodenView]" & _
" WHERE [OpretDato] >= ? AND [OpretDato] < ?" & _
" AND (Jurist NOT IN ('BF','MLT','NL') OR Jurist IS NULL)" & _
" ORDER BY [Jurist] ASC ;"
' COMMAND OBJECT (BINDING PARAMETERS)
With cmd
.ActiveConnection = conn ' CONNECTION OBJECT
.CommandText = strSQL
.CommandType = adCmdText
.Parameters.Append .CreateParameter("s_param", adDate, adParamInput, , StartDate)
.Parameters.Append .CreateParameter("e_param", adDate, adParamInput, , EndDate)
End With
' BIND TO RECORDSET
Set rst = cmd.Execute
...
I have this data :
*Week,Year,Value are in Number format
I am trying to get the average value of the last 5 weeks: 5,000 (i.e. 25,000/5)
So far I have this query
x= user input/get last week in the current year (current Week)
y= current date, in year
INSERT INTO RR5 ([ID],[RR5])
SELECT ID, ROUND((SUM(AMOUNT)/5),4) AS RR5
FROM resultTable
WHERE Years =" & y - 1 & " and Week > " & 52 - (x - 5) & " Group BY ID"
But, I can only get week 51 and 52. I need to put the additional condition to tell the compiler i need week > 50 year 2016 and week < = 3 year 2017.
Years = " & y & " and Weeknum < " & x
to get the Week 1 2 and 3.
I don't think I could put those 2 conditions in the same "where". How do I solve this?
Solution :
INSERT INTO RR5 ([ID],[RR5]) SELECT ID, ROUND((SUM(AMOUNT)/5),4) AS RR5 FROM resultTable WHERE (Years = " & Y - 1 & " and WeekNum > 52 - (5-" & x & ")) OR ( Years = " & Y & " and Weeknum <= " & x & " ) Group BY ID
simply add parentheses on each condition and connect it with OR for the other condition.
Thank you for your support hope it helps anyone with same issue.
You're root trouble is caused by how you are storing your date data. Instead of Year and Week, it would be better to store this as an actual date. However, as a workaround you can convert the existing year and week to a date, and then use that in the where clause.
WHERE (CDate("1 JAN " & Year) + (Week - 1) * 7) > (CDate("1 JAN " & y) + (x - 1) * 7)
What this is doing is it will take each record you have and use the CDate function to turn it into 1 January of the given year. Because these dates are really stored as Double numbers where 1 corresponds to 24 hours, I then add to the 1 January date to find out what the first day of the week is for each subsequent week. (Week - 1) assumes that the first week starts on 1 January.
Now, you just use the same logic for the year (y) and week (x) provided by the user. The query will return anything that occurred later than the date the user specified.
You could use:
INSERT INTO RR5 ([ID],[RR5])
SELECT ID, ROUND((SUM(AMOUNT)/5),4) AS RR5
FROM
(SELECT TOP 5 *
FROM resultTable
WHERE Years * 100 + WeekNum <= SelectedYear * 100 + SelectedWeek
ORDER BY Years Desc, WeekNum Desc)
How do I get the whole date difference in VBA?
I know that to get the year or the month or the day I do:
DateDiff("yyyy", Me.DateofBirth, Me.Year).
I want the whole difference. Not just the year, and the two columns that I have are Date of Birth and Year.
Dates are stored internally in VBA as doubles, with the integer portion as the number of days since 1/1/1900. To get the difference between two dates, you can just subtract them:
Dim dob As Date
dob = DateSerial(1990, 1, 1)
Dim difference As Date
difference = Now - dob
Debug.Print Year(difference) - 1900 & " years, " & _
Month(difference) & " months, " & _
Day(difference) & " days."
If you want the total number of days, you can just subtract them and use the numeric value of the underlying double:
Dim dob As Date
dob = DateSerial(1990, 1, 1)
Dim days As Long
days = Now - dob
Debug.Print days & " days."