I have a table full of items that each have a unique ItemID. There is another table with information on tests that are done on these items around once a month (some may have multiple tests per month and some may have none some months) and each test entry has a full date mm/dd/yyyy. I would like to display the average of one of the fields over all the data on a monthly basis. So assuming what I'm averaging is the item weight, I want to end up with a table like this:
Date AvgOfWeight
1/09 24.55
2/09 28.64
3/09 22.39
and so on...
I know that I can do a query to do averages and I can group the averages by certain criteria, but is there an easy way to group mm/dd/yyyy dates by month?
I love this strzero function that can be used here this way:
m_monthYear = strZero(year(date()),4) & "-" & strZero(month(date()),2)
Results look like 2009-09 and can be ordered ascending, as they begin with the year. You'll just have to create this strZero function as follows:
Public function strZero(x_myLong as long, x_length as integer) as string
Dim m_strZero as string
m_strZero = trim(str(x_myLong))
do while len(m_strZero) <= x_length
m_strZero = "0" & m_strZero
loop
strZero = m_strZero
end function
This was written on the fly. Please check all parameters (if any) for str, add error management, and adapt to your own needs. You might like to pass x_myLong as a variant, in order to return a '0000' string for example. This function has multiple other uses when converting numbers to fixed length strings.
Related
I am using Microsoft report builder.
I have columns in a column group that are grouped by weeks. One of the field of this scope should be subtraction of one column value from current week minus column value from another week. Is this possible in ssrs?
rough dataset:
Create table #Test
(
JobNum [nvarchar](20)
,YearNumber int
,WeekNumber int
,Column1 int
)
insert into #Test
VALUES
('job1',2022,1,10),
('job2',2022,1,50),
('job1',2022,2,15),
('job2',2022,2,60),
('job1',2022,3,20),
('job2',2022,3,70)
select * from #Test
drop table #Test
and groups in builder
Onestly I don't know if this is possible (I don't think is possbile to access the scope of the "previous group") but maybe you can use this workaroud.
0. Start dataset
I've started from this dataset, somehow similar to yours
And this is the tablix object
1. Create a calculated field on your dataset
Create a new simple filed in your dataset to have for each week number the previous week number
=Fields!Week.Value - 1
2. Add a custom function to sum the result of a LookupSet
Follow this guide to add this custom function to the report enabling us to sum the result of a LookupSet function (many thanks to the author!). We will use this in the next point.
Function SumLookup(ByVal items As Object()) As Decimal
If items Is Nothing Then
Return Nothing
End If
Dim suma As Decimal = New Decimal()
Dim ct as Integer = New Integer()
suma = 0
ct = 0
For Each item As Object In items
suma += Convert.ToDecimal(item)
ct += 1
Next
If (ct = 0) Then return 0 else return suma
End Function
3. Add a costum expression for the column 2
=
Sum(Fields!Value.Value) -
Code.SumLookup(LookupSet(Fields!PreviousWeekNumber.Value,Fields!Week.Value,Fields!Value.Value, "DataSet1"))
The LookupSet function retrive the set of values in the selected table/scope (Dataset1 in the example) wich have the week number equal to the previuos week number (in our the default scope, the column group scope). The custom function "SumLookup" enable us to sum the VariantArray (or Nothing if there is no match) returned by the LookupSet function.
4. Results
This is the result:
if you need a different result for the first week just add a condition to the custom expression for the column2
EDIT
If you have also a row group like this:
You can modify the previuos expression to this:
=
Sum(Fields!Value.Value) -
Code.SumLookup(LookupSet(Fields!JobNum.Value & Fields!PreviousWeekNumber.Value,Fields!JobNum.Value & Fields!Week.Value,Fields!Value.Value, "DataSet1"))
Achivieng a LookupSet based on multiple conditions.
I have a form called FirstInLastOut which looks as the image below.
Based on Name or badge number I want to search between two dates.
I am using the following criteria on the query:
>=[Forms]![FirstInLastOut]![StartDateEntry] And <=[Forms]![FirstInLastOut]![EndDateEntry]
This is given me results that include other months as well. Please see the query report below.
So as you can see in the image the numbers of the dates are falling with the the parameter but getting other months as well.
How can I make it so it will only select the dates between the date ranges?
SELECT FistClockInRaw.Badgenumber, FistClockInRaw.name, FistClockInRaw.lastname, FistClockInRaw.MinOfCHECKTIME, FLastClockOutRaw.MaxOfCHECKTIME, [MaxOfCHECKTIME]-[MinOfCHECKTIME] AS TotalHours, FLastClockOutRaw.QDate, FistClockInRaw.MinOfQTime, FLastClockOutRaw.MaxOfQTime, RawCompleteQuery.CHECKTIME
FROM RawCompleteQuery, FLastClockOutRaw INNER JOIN FistClockInRaw ON (FLastClockOutRaw.Badgenumber = FistClockInRaw.Badgenumber) AND (FLastClockOutRaw.name = FistClockInRaw.name) AND (FLastClockOutRaw.QDate = FistClockInRaw.QDate)
WHERE (((FistClockInRaw.name)=[Forms]![FirstInLastOut]![FirstNameEntry]) AND ((RawCompleteQuery.CHECKTIME)>=[Forms]![FirstInLastOut]![StartDateEntry] And (RawCompleteQuery.CHECKTIME)<=[Forms]![FirstInLastOut]![EndDateEntry]));
is the Query
I assume that the forms fields StartDateEntry and EndDateEntry are bound to fields of type date.
I also assume that you are only interested to compare the date part of those form fields.
So try this condition instead to assure correct date interpreting:
WHERE FistClockInRaw.name=[Forms]![FirstInLastOut]![FirstNameEntry]
AND RawCompleteQuery.CHECKTIME >= Format([Forms]![FirstInLastOut]![StartDateEntry], "\#yyyy-mm-dd\#")
AND RawCompleteQuery.CHECKTIME <= Format([Forms]![FirstInLastOut]![EndDateEntry], "\#yyyy-mm-dd\#")
A remark:
Be aware that every date field/variable always contains a time part too!
So your current logic comparing EndDateEntry with <= can cause trouble, because you would only get results of the end date having time values of 00:00:00 in the field CHECKTIME.
If any record of CHECKTIME contains the requested end date and a time part bigger then 00:00:00, it is not in the result.
To avoid that, you should use < and add one day:
And RawCompleteQuery.CHECKTIME < Format([Forms]![FirstInLastOut]![EndDateEntry] + 1, "\#yyyy-mm-dd\#")
I work for a gun club and we are trying to find the total number of targets shot at during a specific year. The table contains totals from years 2000-2018 and I am trying to write a query that will look at the string for the date of the shoot which is in a format like this 2010-06-13 00:00:00.000 I just care about the year so I created this query:
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND ShootDate LIKE '2007-%%-%% 00:00:00.000'
If I run the query up to the AND clause it works and returns a total. However, I get a null value if I highlight the whole thing. I have tried variations of the string as well. Such as this '2007%' and this '2007-- %'
Not sure what I am missing. Any help is appreciated.
Don't convert to string to query for a year, use YEAR() function instead:
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND YEAR(ShootDate)=2007 -- MySQL
You could also use a range query
SELECT SUM(ShotAt) AS TotalTargets
FROM MemberShootsC
WHERE GunClubNumber = 210015 AND ShootDate BETWEEN '2007-01-01' AND '2007-12-01 23:59:59.999'
Note: The above assumes that you do not store dates as strings. The function to use depends on RDBMS. In MS SQL Server you would use DATEPART(year, ShootDate) = 2007
I am wanting to show current month data. But when I am using this query, then generating extra single string from query.
$queryCurentMonth = $this->Bookings->find('all')
->where(["MONTH(Bookings.created)" => "MONTH(CURRENT_DATE())"]);
Generating :
SELECT
*
FROM
`bookings` `Bookings`
WHERE
MONTH(`Bookings`.`created`) = 'MONTH(CURRENT_DATE())'
This = 'MONTH(CURRENT_DATE())' , it is generating blank data. How we can perfect this query.
MySQL is treating your RHS value as string in
MONTH(`Bookings`.`created`) = 'MONTH(CURRENT_DATE())'
'MONTH(CURRENT_DATE())' shouldn't have single quotes around it. Instead it should be like this
MONTH(`Bookings`.`created`) = MONTH(CURRENT_DATE())
Try to compare year also as function MONTH() returns only a number 1 through 12, the query would return all records for a Month of all years, rather than only the current year. Use both MONTH(), YEAR() to compare months for the current year.
MONTH(`Bookings`.`created`) = MONTH(CURDATE()) AND YEAR(`Bookings`.`created`) = YEAR(CURDATE())
Finally, I have got a solution. it is working finely now.
$queryCurentMonth = $this->Bookings->find('all')
->where(["MONTH(Bookings.created)" => date("m")]);
I have a table, tblCandidates, with field PacerCallDuration_1 of type Date/Time. I would like to find the average time of the calls between today and today - DateRng. DateRng is an integer of how many days I want to go backwards in data, e.g. 30.
Dim PCD1 As Date
Dim DateRng as integer
Dim AvgCallTime As Date
AvgCallTime = DoCmd.RunSQL "select cdate(AVG([PacerCallDuration_1]))_
from tblCandidates"
It does not like my SQL statement and and other items in that line I have tried.
Searching the site I find "How can I get the average of a date field?" was close but not close enough.
Thank you for your help.
You can use DAvg:
DateRng = 5 ' for example.
AvgCallTime = DAvg("[PacerCallDuration_1]","tblCandidates","[CallDate] Between DateAdd('d', -" & DateRng & ", Date()) And Date()")
where CallDate is ... the call date.