Create a sql query based on selected month from dropdown combobox in excel userform - sql

I have a userform in excel for attendance reporting. On the form the user chooses the employee they want to review, and then they can check a box that says year to date, or select individual months from a combobox drop down. This is all to query our sql server that has the data on it. Year to date is easy, because I know how to use the variables for current date and first day of the year. What I'm having trouble with is how to convert the user's month selection into a usable query. For example: If the user selects January for the drop down, the query would be
select * from [dbo.mytablename]
where [agent name] = '<value from a textbox that I know how to pass in>'
and [cal date] > '1/1/2018' and [cal date] < '1/31/2018'
Right now my only idea is to have cells on a holding spreadsheet in the workbook that have the first and last day of each month and then use the cell values. But I'd like to avoid that if possible. If you have any ideas that would be great!

First of all
and [cal date] > '1/1/2018' and [cal date] < '1/31/2018'
will select all data from Jan 1 to Jan 30 and not include any data from Jan 31.
Keeping this in mind, the check should be
and [cal date] > '1/1/2018' and [cal date] < '2/1/2018'
So if you do get a month from drop down you can do something like below
select * from [dbo.mytablename] t
join
(values
('Jan', 1),('Feb',2),('Mar', 3),
('Apr', 4),('May',5),('Jun', 6),
('Jul', 7),('Aug',8),('Sep', 9),
('Oct', 10),('Nov',11),('Dec', 12)
)v(mon,num)
on v.mon='<month name received from a text box>'
t.[agent name] = '<value from a textbox that I know how to pass in>'
and t.[cal date] > cast(cast(v.num as varchar)+'/1/2018' as date)
and t.[cal date] < cast(cast((v.num+1)%12 as varchar)+'/1/'+ cast(2018+ (v.num/12) as varchar) as date)

In SQL Server there are numerous techniques for date calculation/converions. If 2012+ you can use EOMonth() or DateFromParts().
I should also add [cal date] < '1/31/2018' should be [cal date] <= '1/31/2018'
Example
Select StrCast1 = try_convert(date,concat('January',' 1, ',2018))
,StrCast2 = EOMonth(try_convert(date,concat('January',' 1, ',2018)))
,FromParts1 = DateFromParts(2018,1,1)
,FromParts2 = EOMonth(DateFromParts(2018,1,1))
Returns
StrCast1 StrCast2 FromParts1 FromParts2
2018-01-01 2018-01-31 2018-01-01 2018-01-31

Assuming your month is a numeric value between 1 and 12, you can use something like
Dim fromDate As Date, toDate As Date
fromDate = DateSerial(2018, month, 1)
toDate = DateSerial(2018, month + 1, 1)
Debug.Print fromDate, toDate
This will work even with December, DateSerial accepts a 13 as month.
Note that you have to ask for < first day of next month to catch data from the last day of the month.
Side note: I assume you use a ADODB.Command to query the database. I would strongly suggest that you use ADODB.parameter to pass the dates (and the agent name) to the database - you don't have to deal with formatting or converting the dates so that the database understand them correctly. See for example https://stackoverflow.com/posts/10353908/edit to get an idea how this works.
Update
I assume you fill your combo box with values from a range and the value is linked to a cell. Use for example the match function to get the month as number (I would never trust that the name of a month is translated correctly by Excel or the database, there are too many things like regional settings that could cause that it breaks).
Assuming:
Range with month names: A1..A12
Linked cell: B1
Put the formula =MATCH(B1,A1:A12) in cell B2. VoilĂ , you have the number of the month.

Related

Making new column based on date with variable year

As topic is saying, it all should apply to dates with variable year.
I would like to make a new column (called which_part for example) saying if the date (in this case date is in "sil.sales_invoice_date") is between 1st of january to 30th of june - which should say H1 (half 1) and else is H2 (between 1st of july to end of the year).
I've tried doing something like that with convert
SELECT
sil.sales_invoice_date AS "Distributor Invoice Date",
CONVERT(sil.sales_invoice_date, #year + '-01-01') AS [start year],
CONVERT(sil.sales_invoice_date, #year + '-06-30') AS [end year],
It doesn't work at all and I can't write [half year] in there.
I've also tried to do it by using
case sil.sales_invoice_date between
But I don't really know how to format it to work with variable year.
if you have date in format dd.mm.yyyy
Try this
Case when substr(sil.sales_invoice_date,1,5) between '01.01' and '30.06' then 'H1'
else 'H2'
end as which_part;

MS SQL How to get the next month if its december

Hi I wanna get the next month in SQL server but what if the month is 12.
when i have date = '2016-10-04' then the next month will be date = '2016-11-04'.
I want to put this into this query :
if EXISTS(
select * from month
where id_Prod = #id_Prod
and datepart(month,DATEADD(month,1,_date)) = datepart(month,DATEADD(month,1,_date))
and datepart(YEAR,_date) = datepart(YEAR,#date)
);
you can try dateadd
declare #dt date = getdate()
select datepart(MM,dateadd(mm,1, #dt))
If the spec I've given in the comments is correct, you want something along the lines of:
if EXISTS(
select * from month
where id_Prod = #id_Prod
and _date >= DATEADD(month,DATEDIFF(month,'20010101',#date),'20010201')
and _date < DATEADD(month,DATEDIFF(month,'20010101',#date),'20010301')
);
The DATEADD,DATEDIFF pairs are just being used to generate "the 1st of next month" and "the 1st of the month after that", using arbitrary (fixed) dates to compute those. E.g. the first line computes how many whole months have occurred between 1st January 2001 and #date. It then adds that number of months onto 1st February 2001. This expression should therefore always generate the 1st of the month that comes after #date. The second pair does the same but adds the computed number onto 1st March instead.
You should also note that I'm not applying any functions to _date, so if there happens to be a useful index on that column, it should be usable for this query.
This seems pretty simple,
Get Previous date of current date
SELECT DATEADD(MONTH,-1,GETDATE()) AS PrviousDate
Get Next date of current date
SELECT DATEADD(MONTH,1,GETDATE()) AS NextDate

SSRS SQL I need to display data for dates used in the parameter and the previous month

I have an SSRS report with parameters for Created On Start and Created On End. Users run this manually and choose the date range to display records for. I need to display in two different columnns the records for the month the user entered in the parameters and the previous month for the dates used in the parameters.
For example the user uses the the following dates in the parameters:
Start Date: 03/01/2016 EndDate: 03/31/2016
The Report should display in one column the records for march 2016 and next to it the records for february 2016
You could write one query which queries both months.
Add a field that will act as the column label eg format the date as the first of the month.
Then create a pivot table to show the two months as the columns with the usual rows .
EDIT - new details
So:
dateStart = '2016-03-01'
dateEnd = '2016-03-31'
These could be less than the whole month, but should be in the same month. prevStart = DATEADD(month, DATEDIFF(month, '2000-01-01', dateStart)-1, '2000-01-01')
the first day of the previous month.
Use similar for the prevEnd to calculate the last day of previous month.
OK. Now build your select:
SELECT xxxx, yyyy, zzzz
, DATEADD(month, DATEDIFF(month, '2000-01-01', createdOnDate), '2000-01-01') as MonthCol
FROM tables
WHERE (createdOnDate>= prevStart and createdOnDate<=prevEnd)
OR (createdOnDate>= dateStart and createdOnDate<=dateEnd)
Build a pivot table style grid with monthCol as the heading of the columns and your usual data as the rows. That way you can get your "previous Month" columns as well as the date range that you selected

Select Date range between two months

My table has one [date] column and would like to filter dates between March to auguest for any year.
Here is my functions, but none of them work and returns all data.
iif(CDate([Date]) between DateAdd ("m",3, CDate([Date])) And DateAdd ("m",7,CDate([Date])),"1","0")
iif([Date of Activity] between (DatePart("m", [Date of Activity]) = 4) And (DatePart("m", [Date of Activity]) = 8),"1","0")
Date is a reserved word and should not be used for a field name. That said, the following should work if your field is a date/time field and not text. Month() Between 3 and 8

Getting the first and last dates in a month

I have two comboboxes that lets the user select a date and year. What I want to do is to translate this into my query in access, which requires a [start date] and an [end date] parameter.
I.E. user picks "May" and "2013" in the combo boxes
My query is setup between [start date] and [end date], so I want to translate this month and year selection from the combo boxes into two strings (startdate and enddate, then pass them as command parameters) that contain MM/DD/YYYY, MM/DD/YYYY. What is the best way to take two strings and get the first valid day and last valid day. I have:
FirstDayInMonth = DateSerial( _
Year(Date), Month(Date), 1)
LastDayInMonth = DateSerial( _
Year(dtmDate), Month(dtmDate) + 1, 0)
But I need to make the switch from a string into a date format to get back the first/last day of the selected month, using only the month ("MAY") and year ("2013")? Am I missing something relatively simple?
Make the "Month" combo box have two columns (Column Count property is 2):
1 | Jan
2 | Feb
...
12 | Dec
Set the Bound Column of the combo box to 1 so its .Value is the month number, but display only the month name (hide the number) by setting the width of the first column to zero:
Column Widths: 0";0.75"
So, do you get the month and year (as integer or long, not a date yet) from the comboboxes?
Then try this:
Dim m As Long
Dim y As Long
Dim d_from As Date
Dim d_until As Date
m = CLng("01") ' get these two from your comboboxes
y = CLng("2013")
d_from = DateSerial(y, m, 1)
d_until = DateAdd("m", 1, d_from)
d_until = DateAdd("d", -1, d_until)
When you have the first date, you calculate the second (last day in month) by adding one month, then going one day back.