Count items and group by a datetime unit - javascript

I'm trying to organize a query which should print a count of items ordered by a time unit such as a hour, a day etc.
My limitation is that I'm using LovefieldDB javascript library and complex queries are limited.
I have a table of Units where the main field is the date of creation like this:
2017/11/29 08:17
2017/11/29 08:47
2017/11/29 09:25
2017/11/29 11:39
The result I expect is to count per hour the number of items:
08:00 (2)
09:00 (1)
11:00 (1)
What I want to avoid is to select all rows and process them in a loop because this software is going to have thousands of rows and I'll have to create similar queries for day, month and also year.
A possible solution I thought is to add 4 more datetime fields where I would save created_hour, created_day, created_month, created_year so I can order them easly.
Do you have some tips?

This is what I mean. You can format the time to be in hours and group by the formatted time.
SELECT DATE_FORMAT(datecolumn, '%H:00'), COUNT(*)
FROM SOURCETABLE
GROUP BY DATE_FORMAT(datecolumn, '%H:00')

Related

How to sort array of strings representing dates based on calendar week

I have an array of strings in this format: "2023-01-30". The dates range from past, to present, to future. I want to sort the dates into separate arrays based on the work weeks (monday through friday) that they fall into with past weeks falling into the present week.
For instance, given the array ["2022-02-15", 2023-01-30", "2023-02-03", "2023-02-06", "2023-02-14"] I want to sort into a 2d array with the first array being this week and all past events, and following arrays being subsequent weeks: [["2022-02-15", 2023-01-30", "2023-02-03"], ["2023-02-06"], ["2023-02-14"]]. I'm trying to use the js Date() object to accomplish this but something in my logic is off. Thanks in advance!

MySQL way to store monthly revenue

I want to store restaurant's monthly revenue (income and expenses), and later show it on a line graph for every year. I have come to this workaround I would store in year variable for example 2020-01-01 and then it should be adding values to all the following row for every month. Would it even work this way? Or should I use one date type and add months to it?
It can work, but it is not optimal.
For example if you want to see the yearly expenses you have to type every single month name into your query.
A more practical solution can be to use a single table with example columns like so:
date
is_expense (boolean)
amount (double)
restaurant_id
Where is_expense is boolean if the amount is income or expense.
You can aggregate from here everything: yearly / monthly expenses/incomes/profits etc.
You can use MySQL Functions like MONTH(date) that will give you specific month. For example if you want to aggregate all expenses for specific year & month you will do something similar to
SELECT SUM(amount) from Table WHERE is_expense=1 AND MONTH(date) = 1 AND YEAR(date) = 2020

Generate JSON result from MySQL database with total number of records per day for a Task record?

I am wanting to use this JavaScript library https://kamisama.github.io/cal-heatmap/ to generate an Event style heatmap like GitHub uses.
I plan to use it to represent how many actions occur on my Project Management application per day on a Task record.
For example each square will be 1 day. It's color and number of items shown when you hover a square will be the total number of activities performed on that Task record for that day.
A Task activity includes:
task title, description, due date, milestone, priority, assigned user, or tags being updated.
Comment or comment reply being posted on the task record.
So on 6/17/2015 if 5 comments are made on a Task and the assigned user field is updated. It would show 6 items for that days square on the generated heatmap.
What I need help with is generating the JSON that will generate the Heatmap for each Task record.
I will be pulling the Task Activities for a Task from a MySQL Database.
So I should be able to query the database to count all records created in my activity DB table per day on a Task.
My Heatmap start and end dates will be the start date set as the date the Task record was created. The End date will be today's date.
Assuming my MySQL Database structure looks like this:
Table name: task_activities
activity_id
task_id
activity_type
created_datetime
So I will need to count the total number of records per day whre the task_id = the Task record I am building the JSON output for.
The JSON output needs to be in this format:
{
"timestamp": 5,
"timestamp2": 2,
"timestamp3": 4,
...
}
The timestamp needs to represent the day and the value will be the total number of MySQL Activity records on that day for that Task ID.
Can someone help me to generate the desired MySQL to generate a JSON result in that format where each day is a Timestamp value and the number is the total number of activities for that task record on that given day?
You want to bring the data together by date, irrespective of the time of day, but the date element in each row includes a time. Thus, you need to extract the date portion of the date_created field:
SELECT DATE_FORMAT(DATE(`date_created`), '%Y-%m-%dT00:00:00') AS `date`,
COUNT(`event_id`) AS `count`
FROM `task_activities`
WHERE `task_id`='242'
GROUP BY DATE(`date_created`);
The GROUP BY DATE() fragment uses just the date part as the grouping element. The DATE_FORMAT() fragment returns the date formatted in a custom way. Refer to the MySQL date & time documentation for the modifiers available.
Here is an SQL fiddle demoing the behavior.

Calculate actual number of days from series of date ranges

I need to calculate the actual number of days between a number of date ranges.
eg:
2014-01-01 to 2014-01-04 is 4 days
2014-01-05 to 2014-01-06 is 2 days
while
2014-02-01 to 2014-02-03 3 days
with
2014-02-03 to 2014-02-05 3 days
is a total of 5 days
an added complication is that during a month there will be some gaps between date ranges and or overlapping date ranges to be taken into consideration
any ideas guys.
ability to do the calc using mysql would be great.
Maybe i should have said count the number of days instead of calculate.
I can get the number of days between two date ranges using either mysql or javascript as mentioned below, I think my wheels are coming off with the overlapping date ranges where one range starts before another has finished.
As suggested HERE:
You can use Date objects in Javascript:
var prevTime = new Date(2011,1,1,0,0); // Feb 1, 2011
var thisTime = new Date(); // now
var diff = thisTime.getTime() - prevTime.getTime(); // now - Feb 1
alert(diff / (1000*60*60*24)); // positive number of days
EDIT: I missed you tagged JavaScript, but asked for MySQL
As suggested HERE:
If you are using DATE or DATETIME formatting for your column, you can use:
SELECT DATEDIFF(STR_TO_DATE('2014-01-01', '%Y-%m-%d'),STR_TO_DATE('2014-01-04', '%Y-%m-%d')) AS DAYS
Hope that helps
EDIT2 Here's a nice way to do it in one statement with some logic:
SELECT (CASE
WHEN Start_date1 <= End_date2 THEN
1+DATEDIFF(End_date2, Start_date1)
WHEN Start_date2 <= End_date1 THEN
1+DATEDIFF(End_date1, Start_date2)
ELSE 0
END) AS DAYS
FROM TABLE
The logic is:
Date1 starts before Date2 ends, Start_date1 >= End_date2
OR
Date2 starts before Date1 ends, Start_date2 >= End_date1
If neither is true, they don't overlap.
This little snippet of SQL request code may get you started. It uses DATEDIFF():
SELECT 1+DATEDIFF(MAX(end_date), MIN(start_date)) AS duration_in_days, event_id
FROM event_table
GROUP BY event_id
What's going on here?
First, you've said that the range 21-Aug-14 to 22-Aug-14 is 2 days, but DATEDIFF computes it as 1. So we need to add 1 to it.
Second, the GROUP BY here will aggregate multiple date ranges, if any, for the same event. I have no idea if you're using events; you didn't say. The point here is to show how to aggregate these dates.
Third, if your individual date ranges are non-overlapping, this query won't work correctly. For example, suppose you have these two date ranges
21-Aug-14 to 22-Aug-14
27-Aug-14 to 28-Aug-14
This query will come up with the aggregate range 21-Aug-14 to 28-Aug-14, which is eight days. But you may want to omit the gap 23-Aug to 26-Aug, and only report 4 days. This query won't do that.

javascript - predict/estimate next number from a dataset

Math isn't really my thing, but what I'm trying to figure out is how to predict/estimate the next number from a dataset.
Let's say I have an array:
var values = new Array(1,4,3,5,6,10,4,15);
Does anyone know a formula in javascript that could guess the next number after 15 based off the previous values in the array.
Basically I have an array of total numbers from daily sales, each item in the array is the total for a single day. So I'd like something that could guess what tomorrow's sale might be.
Based on the data you're providing, it seems you can only predict what tomorrow's sale might be by taking the average of your dataset.
If you had additional data, say, day of the week, you could take the average of all sales on Tuesdays, and then make a prediction based off of that average.
Have a look at the various moving average methods - you can choose whichever suits your application best.

Categories

Resources