Query MS Access multiple condition (where) - sql

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)

Related

Get first & last date for next 12 months in sql in datetime format

I am trying to get first date & last date for next 12 months from the date the report/query is run.I was able to get next 12months by using below query but not with first and last dates. Any suggestions on how to do this are appreciated.
SELECT STR(MONTH(DATEADD(mm,Number,GETDATE())),2)+'/'
+ STR(YEAR(DATEADD(mm,Number,GETDATE())),4),DATEPART(MM,'january '+'01 1900')
FROM Master.dbo.spt_values
WHERE NAME IS NULL
AND Number BETWEEN 0 AND 11
But results it gives are:
But what I expect:
Assuming EOMONTH function is supported, use
SELECT dateadd(day,1,dateadd(month,number-1,EOMONTH(getdate()))) as mth_start,
dateadd(month,number,EOMONTH(getdate())) as mth_end
FROM Master.dbo.spt_values
WHERE NAME IS NULL
AND Number BETWEEN 0 AND 11
Try this query
SELECT
CONVERT(datetime, STR(MONTH(DATEADD(mm,Number,GETDATE())),2)+'/01/'+ STR(YEAR(DATEADD(mm,Number,GETDATE())),4)) firstdate,
dateadd(day,-1,CONVERT(datetime, STR(MONTH(DATEADD(mm,Number+1,GETDATE())),2)+'/01/'+ STR(YEAR(DATEADD(mm,Number+1,GETDATE())),4))) lastdate
FROM Master.dbo.spt_values
WHERE NAME IS NULL
AND Number BETWEEN 0 AND 11
to fetch last date of month, we can remove one day from first date of next month.

VBA to find Second sunday for March every year

I have an if condition in my VBA code to check if it is spring Day light savings day, which is the second Sunday of March. The below code works for all except when 3/1/2015 (for example) is Sunday, then this shows 3rd Sunday. I can add another condition to check if it is Sunday then don't add 7 to the formula, but is there a better way of doing this?
If my_date = (DATEVALUE("3/1/" & this_year) + 7+ CHOOSE(WEEKDAY(DATEVALUE("3/1/" & this_year), 1),7,6,5,4,3,2,1))
This works:
For VBA :
DateSerial(this_year, 3, 1) + 6 - WorksheetFunction.Weekday(DateSerial(this_year, 3, 1), 3) + 7
For Excel:
DateSerial(this_year, 3, 1) + 6 - Weekday(DateSerial(this_year, 3, 1), 3) + 7
Enter the year you want to look at in Cell A1, then select a cell where you want to see the date of the 2nd Sunday in March for the given year and run this code:
Sub test()
Dim i As Integer
Dim dt As Date
Dim y As Integer
i = 0
y = Range("A1").Value
dt = "3/1/" & y
While i < 2
If WeekdayName(Weekday(dt), False, vbUseSystemDayOfWeek) = "Sunday" Then
i = i + 1
If i <> 2 Then
dt = DateAdd("d", 1, dt)
End If
Else
If i <> 2 Then
dt = DateAdd("d", 1, dt)
End If
End If
Wend
ActiveCell.Value = dt
End Sub
I thought I would just add this below code for anyone else who comes across this. I wanted to create a GENERAL purpose block of code that gets any day of week of any month. Ie. if I want the second Sunday or the last Sunday I could retrieve this from one function. Thus I have written the below. You can alter it to how you need it. Ie. Sunday/ Monday or first, second or third etc. This is done by cycling through the days of the month and if the day return which ever day of week you are looking for you save the day in a collection. Once your have cycled through the month you then cycle through the collection to retrieve the necessary date you need!
Function DayOfMonth(theDate As String) As String
'cycle through the given month
'check each day of month and if sunday add day of month to collection
'then cycle through collection for required sunday of month
'daylight savings only happens in march and november
On Error Resume Next
Dim i As Long
Dim testDate As String 'this get passed through function
Dim theYear As Long, theMonth As Long
Dim dayCollection As New Collection
theYear = Year(theDate)
theMonth = Month(theDate)
'build collection of sunday's day of month
For i = 1 To 31
testDate = i & "/" & theMonth & "/" & theYear
If Weekday(testDate, vbSunday) = 1 Then
dayCollection.Add i
End If
Next i
For i = 1 To dayCollection.Count
'2nd sunday
If i = 2 Then
DayOfMonth = dayCollection(i) & "/" & theMonth & "/" & theYear
End If
'last sunday of month
If i = dayCollection.Count Then
DayOfMonth = dayCollection(i) & "/" & theMonth & "/" & theYear
End If
Next i
'clear collection
Set dayCollection = New Collection
End Function
Cheers!
Here's a slight modification to Slubee's answer which I find a little more elegant and easier to follow:
DateSerial(Year, 3, 1) - WorksheetFunction.Weekday(DateSerial(Year, 3, 1), 2) + 14
The 1st term = the date value of March 1st
The 2nd term = a number between 1(Monday) and 7 Sunday)
So (1st term minus 2nd term) gives you the last Sunday in February... and clearly adding 14 will get you the second Sunday of March.
With this structure, the formula can more easily be adapted to similar use cases such as the start/end of daylight saving time in Europe (last Sunday of March/October) or the end of USA DST (first Sunday of November).
If you start from the last day of the previous month, you can correctly calculate the second Sunday of the target month, even if it begins on a Sunday.
The following code sample calculates the start and end date/time of Daylight Saving Time for US areas that observe DST.
If you are developing a function to do this, be sure to test years like 2020 where March begins on a Sunday.
Dim dteLast As Date
Dim dteStart As Date
Dim dteEnd As Date
' DST starts on the second Sunday in March at 2 AM
dteLast = DateSerial(Year(dteDate), 3, 1) - 1
dteStart = dteLast - Weekday(dteLast) + 15 + TimeSerial(2, 0, 0)
' DST ends on the first Sunday in November at 2 AM
dteLast = DateSerial(Year(dteDate), 11, 1) - 1
dteEnd = dteLast - Weekday(dteLast) + 8 + TimeSerial(2, 0, 0)
If my_date = (DateSerial(this_year, 3, 1) + (8 - Weekday(DateSerial(this_year, 3, 1)) Mod 7) + 7) Then

Find date, given WEEKNUM and WEEKDAY - VBA

I'm trying to find a way of finding a date value, given the WEEKNUM and WEEKDAY
For example
WEEKNUM = 9
WEEKDAY = 4 '(Wednesday)
I can use the below function to find the WEEKNUM from the date, but how can I go the other way around?
Function WEEKNUM(D As Date, FW As Integer) As Integer
WEEKNUM = CInt(Format(D, "ww", FW))
End Function
You could use a table on a hidden sheet, and just used Vlookup to find the correct date. EG
DATE WEEKDAY WEEK NO WEEKDAY + WEEK NO
01/03/2016 Tuesday Week 10 Tuesday 10
02/03/2016 Wednesday Week 10 Wednesday 10
In VBA, you could then look up the name of the sheet, which is the weekday, and got the week number from the filename of the workbook, then use vlookup to find the correct date.
weekNum = Mid(ThisWorkbook.Name, 6, 2)
searchStr = ActiveSheet.Name & " " & weekNum & " " & Format(Now(), "YYYY")
rowNo = Application.WorksheetFunction.Match(searchStr, Sheets("WEEKLIST").Range("D:D"), 0)
strSubject = Format(Sheets("WEEKLIST").Range("A" & rowNo).Value, "DD/MM")

Determine number of days between dates

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."

Datatable compute: filtering by date

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.