Count the average of number of surveys per year, Spring Data Jpa - spring

I have a Model, called Survey that has a
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
private Date submittedDate;
field, which is a timestamp that shows the time that a row is insterted in this table.
What I want to be able to query and show is this :
The total number of rows for every month, 12 months.
And then find the average. Which would be :
(countJan+CountFeb+...)/12; ( cycle through countInEveryMonth, and divide by 12 )
How do I query this using Spring Data Jpa ?
Do I write a method like :
int countBySubmittedDate(Date submittedDate) ? -
but this will count the number of Surveys at a given timestamp?
Thank you.

Whole year average can be:
public interface SurveyRepository extends CrudRepository<Survey, Integer> {
#Query("SELECT COUNT(s) FROM Survey s WHERE (date_field BETWEEN :yearStart AND :yearEnd)")
Long yearAverage(#Param("yearStart") Date yearEnd, #Param("yearEnd") Date yearEnd);
//you may divide it by 12
}
Same can be done for other scenario.

Related

Retrieve data according to timestamp value from Room Database

I'm trying to retrieve entries that were written in the last 2 minutes into the database.
I use the following query:
#Query("SELECT * FROM Contacts where ('now()' - gatt_server_connection_timestamp) <= 120000")
List<Contact> getContactsByGattServerConnectionTimestamp();
However the result I get is the whole database.
What is wrong with this query?
The SQLite date-time functions are described here.
If gatt_server_connection_timestamp is in milliseconds since epoch, this query should work:
#Query("SELECT * FROM Contacts where gatt_server_connection_timestamp >= (1000 * strftime('%s', datetime('now', '-2 minutes'))))
List<Contact> getContactsByGattServerConnectionTimestamp();

Query entity elements by createdAt on specific date range does not work

My entity has createdAt field which is filled by #CreatedDate when the entity is created. This property is of Date type.
class MyEntity {
#CreatedDate
private Date createdAt;
}
I would like to filter out all entities in a List that are in a range from startDate to endDate. The problem is that when I used findAllByCreatedAtBetween(Date startDate, Date endDate); it worked but not for all cases. When the entity is created i.e.: 2019-10-25 14:15:23 I would like to get it also when the user will type as #RequestParam startDate from 2019-10-24 00:00 endDate to 2019-10-25 14:15 and also take this entity. How could I ignore everything that is behind minutes? Is there a way, because when I pass those values as startDate and endDate the entity isn't found, to find it I have to change 14:15 to 14:16.
You can set any parameter without others in LocalDateTime. For example you want handle without minute. You can set your search date parameter like this:
LocalDateTime localDateTime= myDate.atTime(14,15);//The first parameter is for Hour and other one is for minute.
You can find more detail here: Java Time LocalDateTime At Time Functions

Retrieve database records between two weekdays

I have several records in my database, the table has a column named "weekday" where I store a weekday like "mon" or "fri". Now from the frontend when a user does search the parameters posted to the server are startday and endDay.
Now I would like to retrieve all records between startDay and endDay. We can assume startDay is "mon" and endDay is "sun". I do not currently know how to do this.
Create another table with the names of the days and their corresponding number. Then you'd just need to join up your current table with the days table by name, and then use the numbers in that table to do your queries.
Not exactly practical, but it is possible to convert sun,mon,tue to numbers using MySQL.
Setup a static year and week number like 201610 for the 10th week of this year, then use a combination of DATE_FORMAT with STR_TO_DATE:
DATE_FORMAT(STR_TO_DATE('201610 mon', '%X%V %a'), '%w')
DATE_FORMAT(STR_TO_DATE('201610 sun', '%X%V %a'), '%w')
DATE_FORMAT(STR_TO_DATE('201610 tue', '%X%V %a'), '%w')
These 3 statements will evaluate to 0,1,2 respectively.
The main thing this is doing is converting the %a format (Sun-Sat) to the %w format (0-6)
well i don't know the architecture of your application as i think storing and querying a week day string is not appropriate, but i can tell you a work around this.
make a helper function which return you an array of weekdays in the range i-e
function getWeekDaysArray($startWeekDay, $endWeekDay) {
returns $daysArray['mon','tue','wed'];
}
$daysRangeArray = getWeekDaysArray('mon', 'wed');
now with this array you can query in table
DB::table('TableName')->whereIn('week_day', $daysRangeArray)->get();
Hope this help

How to getHourOfDay from a timestamp using java.time?

From a java.util.Date( a timestamp), how can I get the hour of day?
In joda.time I use getHourOfDay().
There are multiple solutions for this. If you wish to use the Java 8 classes from java.time the following you need to covert a Date to one of the DateTime classes. The following can be used to convert a Date to a ZonedDateTime where you then can get the hour:
Date date = new Date();
// Convert to java 8 ZonedDateTime
Date date = new Date();
final ZonedDateTime dateTime = date.toInstant()
.atZone(ZoneId.systemDefault());
// Get the hour
int hour = dateTime.getHour();
Quite verbose as you have noticed but the simple reason for this is that a Date is sort of an Instant
Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).
Another approach is simply to get the field from a Calendar instance.
final Calendar instance = Calendar.getInstance();
instance.setTime(date);
final int hourOfDay = instance.get(Calendar.HOUR_OF_DAY);

Get the the most recent and the one before the most recent item

I have a table with many anniversaries : Date + Name.
I want to display the next anniversary and the one after with Linq.
How can i build the query ?
I use EF
Thanks
John
Just order by date and then use the .Take(n) functionality
Example with a list of some objects assuming you want to order by Date then Name:
List<Anniversaries> annivDates = GetAnnivDates();
List<Anniversaries> recentAnniv = annivDates.OrderBy(d => d.Date).ThenBy(d => d.Name).Take(2).ToList();
If the anniversaries are stored in regular DateTime structs, they may have the 'wrong' year set (i.e. wedding or birth year). I suggest writing a function which calculates the next date for an anniversary (based on the current day) like:
static DateTime CalcNext(DateTime anniversary) {
DateTime newDate = new DateTime(DateTime.Now.Year, anniversary.Month, anniversary.Day);
if (newDate < DateTime.Now.Date)
newDate = newDate.AddYear(1);
return newDate;
}
Then you proceed with sorting the dates and taking the first two values like described in the other postings:
(from e in anniversaries orderby CalcNext(e.Date) select e).Take(2)

Resources