MySQL: How to Count total orders by hour from a specific date range - sql

Customer_placed_order_datetime
01 00:00:20
02 01:00:00
31 23:59:00
I want to count the total number of orders that has been made every hour from 01 - 31 days
example outcome:
01-31 HOUR total_orders
1st hour 500
2nd hour 400

Many RDBMS have functions to format dates and cast to string.
For example, with PostgreSQL, you can use TO_CHAR(date_value, string_format). With this new format date (ask only the yyyyMMdd), you can group and count your orders.
If you tag your RDBMS, I can help you more precisely

Related

How to calculate the time difference in SQL with DATEDIFF?

I am using the DATEDIFF function to calculate the difference between my two timestamps.
payment_time = 2021-10-29 07:06:32.097332
trigger_time = 2021-10-10 14:11:13
What I have written is : date_diff('minute',payment_time,trigger_time) <= 15
I basically want the count of users who paid within 15 mins of the triggered time
thus I have also done count(s.user_id) as count
However it returns count as 1 even in the above case since the minutes are within 15 but the dates 10th October and 29th October are 19 days apart and hence it should return 0 or not count this row in my query.
How do I compare the dates in my both columns and then count users who have paid within 15 mins?
This also works to calculate minutes between to timestamps (it first finds the interval (subtraction), and then converts that to seconds (extracting EPOCH), and divides by 60:
extract(epoch from (payment_time-trigger_time))/60
In PostgreSQL, I prefer to subtract the two timestamps from each other, and extract the epoch from the resulting interval:
Like here:
WITH
indata(payment_time,trigger_time) AS (
SELECT TIMESTAMP '2021-10-29 07:06:32.097332',TIMESTAMP '2021-10-10 14:11:13'
UNION ALL SELECT TIMESTAMP '2021-10-29 00:00:14' ,TIMESTAMP '2021-10-29 00:00:00'
)
SELECT
EXTRACT(EPOCH FROM payment_time-trigger_time) AS epdiff
, (EXTRACT(EPOCH FROM payment_time-trigger_time) <= 15) AS filter_matches
FROM indata;
-- out epdiff | filter_matches
-- out ----------------+----------------
-- out 1616119.097332 | false
-- out 14.000000 | true

Counting readmissions in postgresql

I have a table containing data for a prison facility, of the following format:
Prisoner_id admission date discharge date
---------------------------------------------------
1325 06/13/2014 09/13/2014
1266 05/01/2014 07/02/2014
1325 02/21/2015 07/23/2015
1471 02/26/2014 04/20/2014
1266 10/19/2014 12/22/2014
1325 10/09/2015 11/10/2015
I need to count the number of readmissions of each prisoner; that is, how many times each prisoner has been admitted again to the facility, such that the difference between his admission date (date he entered) the last time he entered the facility and his discharge date (date he was let go) the time before the last is less than 60 days.
This means that if the same prisoner has been admitted 2 times, we count this as 1 readmission if the difference between his admission date of the second time and his discharge date of the first time is less than 60 days.
Moreover, if a prisoner has been admitted 3 times, we count this as 2 readmissions if the difference between his discharge date the third time and his admission date the second time AND the difference between his discharge date the second time and his admission date the first time are both less than 60 days. If one of them is less than 60 days but the other is not, count as 1 readmission. If none of them is less than 60 days, count as zero readmissions.
How can I do this in SQL or PostgreSQL? Your help is really appreciated.
I think you just want lag() and some query logic:
The following gets the groups:
select t.prisoner_id,
sum( (prev_dd > admission_date - interval '60 day')::int ) as num_readmissions
from (select t.*,
lag(discharge_date) over (partition by prisoner_id) as prev_dd
from t
) t
group by prisoner_id;

How to get the difference between the chosen date and 1 month before in SQL

How to calculate the price difference between the chosen date and 1 month before.
Example if user chooses 2/1(Feb 1), it will return the difference between 2/1(Feb 1) and 1/1(Jan 1). This is in SQL and data is daily. Date column has YYYY-MM-DD format.
Sample layout:
Date (YYYY-MM-DD) , Product Name (text), Price (int)
You can use a self-join for this. This query uses the same table twice - t_now includes prices this month; t_then shows last month's prices.
In the standard SQL you can write this
SELECT t_now.product, t_now.price - t_then.price
FROM prices t_now JOIN
prices t_then ON (t_now.date - INTERVAL 1 MONTH = t_then.date
AND t_now.product=t_then.product)
WHERE t_now.date='2018-05-01'
It works in MySQL http://sqlfiddle.com/#!9/f208c5/4
You will need changes to the month calculation for SQL Server - You can use DATEADD(MONTH, -1 date)
If you have many prices per month there will be there will be multiple answers at the end of a short month. There are four days one month before 28th Feb - namely 28th Jan, 29th Jan, 30th Jan and 31st Jan
Input
date product price
2018-05-01 Gadget 100
2018-05-01 Widget 50
2018-04-01 Gadget 20
2018-04-01 Widget 10
Output
product t_now.price - t_then.price
Gadget 80
Widget 40

How to find the leave balance month wise in teradata

I have sample data like this
EmployeeID Begin Date End Date Duration
168835 28/11/2017 28/11/2017 6
168835 31/10/2017 9/11/2017 32
and I want to find the leave taken by this employee month wise,so i have joined with calendar date and i want to summarise this data monthly.For e.g, he has taken leave from 31/10/2017 to 9/11/2017 for 32 hours and 6 hours in 28/11/2017. I want to exclude weekend from 31/10/2017 to 9/11/2017 period. I have used "day of week" flag to exclude the weekends, but now problem is when i roll up the data its giving me incorrect result. basically, i want to data like duration (32+6)=38 and this should be divided no of working days that is 9 in this case, so in oct month my data should be 4.22 and in nov month it should 33.77. can anyone please help me on this.Thanks in advance.

Number of specific one-hour periods between two date/times

I have a table of table records, call it "game"
It has an id and timestamp.
What I need to know is unrelated to the table specifically. In order to know the average number of games played per hour, I need to know :
Total games played for each hour over the date range
Number of hourly
periods between the date range.
Finding the first is a matter of extracting the hour from the timestamp and grouping by it.
For the second, if the date range was rounded to the nearest day, finding this value would be easy (totalgames/numdays).
Unfortunately I can't assume this. What I need help with is finding the number of specific hour periods existing within a time range.
Example:
If the range is 5 PM today to 8 PM tomorrow, there is one "00" hour (midnight to 1 AM), but two 17, 18, 19 hours (5-6, 6-7, 7-8)
Thanks for the help
Edit: for clarity, consider the following query:
I have table game:
id, daytime
select EXTRACT(hour from daytime) as hour_period, count (*)
from game
where daytime > dateFrom and daytime < dayTo
group by hour_period
This will give me the number of games played broken down into hourly chunks for the time period.
In order to find the average games played per hour, I need to know exactly how many specific hour durations are between two timestamps. Simply dividing by the number of days is not accurate.
Edit: The ideal output will look something like this:
00 275
01 300
02 255
...
Consider the following: How many times does midnight occur between date 1 and date 2 ? If you have 1.5 days, that doesn't guarantee that midnight will occur twice. 6 AM today to 6 PM tomorrow night, for example, has 1 midnight, but 9PM tonight to 9 AM two days from now has 2 midnights.
What I'm trying to find is how many of the EXACT HOUR occurs between two timestamps, so I can use it to average the number of games played at THAT HOUR over a time period.
EDIT:
The following query gets the days, hours, and # of games, giving an output as below:
29 23 100
29 00 130
30 22 140
30 23 150
Then, the outer query adds up the number of games for each distinct hour and divides by the number of hours, as follows
22 140
23 125
00 130
The modified query is below:
SELECT
hour_period,
sum(hourly_no_of_games) / count(hour_period)
FROM
(
SELECT
EXTRACT(DAY from daytime) as day_period,
EXTRACT(HOUR from daytime) as hour_period,
count (*) hourly_no_of_games
from game
where daytime > dateFrom and daytime < dayTo
group by EXTRACT(DAY from daytime), EXTRACT(HOUR from daytime)
) hourly_data
GROUP BY hour_period
ORDER BY hour_period;
SQL Fiddle demo
If you need something to GROUP BY, you can truncate the timestamp to the level of hour, as in the following:
DECLARE #Date DATETIME
SET #Date = GETDATE()
SELECT #Date, DATEADD(Hour, DATEDIFF(Hour, 0, #Date), 0) AS RoundedDate
If you just need to find the total hours, you can just select the DATEDIFF in hours, such as with
SELECT DATEDIFF(Hour, '5/29/2014 20:01:32.999', GETDATE())
Extract not only the hour of the day but the day of the year (1-366). Then group on those. If there is the possibility the interval could span a year, then add the year itself and group by all three.
year dy hr games
2013 365 23 115
2014 1 00 103