mysql query of coverage [closed] - mysql

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So I have a table of entries with a startdatetime and enddatetime, I want to be able to see overlap like employee coverage. For instance I have 10 employees on shift with different start times and end times and I want to be able to query by hour and see how many employees are available per hour.
I had not tried because I did not find a place to start, I do something similar when they is incoming tasks at a specific time to see how many in each hour, but I am trying to see coverage in each hour of the day based on when an employee starts and ends, like 8 hour shift, 12 hours shift, etc.. So That I can see that I have 2, 3, 4, etc... coverage and map to number of tasks that come in and are planned. Something below looks promising but its only for 1 time for each query, would like a query that can bring back each hour and how many cover in each hour.
Any help would be great.

Try something like this:
SELECT count(*) as TOTAL
FROM table
WHERE '2015-05-28 12:00:00'
BETWEEN startTime and endTime
Obviously you need to change this '2015-05-28 12:00:00' with the desidered date/time you're looking for.
Add others condition if needed...
EDIT
Adding the extra request:
Grouping by date and hour gives you the total count of coverage in a single hour per day.
SELECT date(date_start) as DAY, hour(date_start) as HOUR, count(*) as TOTAL
FROM table
group by date(date_start), hour(date_start)
You can abviously add one or more condition.
ie. in this example below you'll get the total rows per hour in a single day (specified)
SELECT date(date_start) as DAY, hour(date_start) as HOUR, count(*) as TOTAL
FROM table
WHERE date('2015-05-28') = date(startTime)
group by date(date_start), hour(date_start)

Related

Conditional SQL Query Which Sums ALL TimeEntires of Related Task if any TimeEntries Updated in Last 10 Days [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a database with columns
timeEntryIDs (Primary KEY),
taskAssignmentIDs,
Spent(Sum of two columns product), and
updatedAT.
It has multiple timeEntries for every taskAssignmentID all added/updated at different dates.
I am trying to build an SQL query that I can run on a weekly basis to give me the TOTAL spent on every taskAssignmentID where updatedAT is greater than today's date minus 10 days.
So basically if a timeEntry has been made or updated in the last 10 days, provide the new total Spent on that taskAssignmentID.
I have tried and failed to come up with this, any help would be appreciated. Here is the best I could do:
SELECT projectName
, projectID
, clientName
, clientID
, taskName
, taskAssignmentID
, SUM(userAssignment_hourlyRate * roundedHours) AS 'Spent'
, updatedAt
FROM DB
WHERE updatedAt > ADDDATE(CURRENT_DATE(), -10)
GROUP
BY taskAssignmentID
The problem with this is it only SUMS time entries updated in the last 10 days. I want ALL time entries for a given taskAssignmentID IF any timeEntry pointing to that taskAssignmentID has been updated in the last 10 days.
Really appreciate it!
You can use a having clause:
select taskassignmentid, sum(userassignment_hourlyrate * roundedhours) as spent
from mytable
group by taskassignmentid
having max(updatedat) >= current_date - interval 10 day
This computes the overal spent for each taskassignmentid whose latest updatedat is less than 10 days old.
Notes:
I fixed the original code to make it a valid aggregation query; the columns in the select and group by clause must be consistent: every non-aggregated column in the select clause must be repeated in the group by clause (left alone functionaly-dependent columns - but your question does not mention that)
don't use single quotes for identifiers (such as column aliases)! They should be used for literal strings only; use backticks for identifiers, or better yet, use identifiers that don't need to be quoted

How to calculate duration when the clock resets? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
What I want to do is simple
I have a df full of start_times & finish_times.
All start & finish in the same day except 2 rows
The time is in a 24 hr format
I want to calculate the min, max, & avg of the calculated time duration.
The problem is out of the 230 rows, 2 of the elapsed times reset.
e.g. One Start time is 2020-10-14 23:37:26 & its corresponding finish time is 2020-10-15 00:19:47
and I have another row where the exam starts 1 day & finishes the next
I stored the values as DATETIME
How do I go about converting this to my desired output?
SELECT AVG(SEC_TO_TIME(TIMESTAMPDIFF(MINUTE, Start_Time, Finish_Time))) AS
Avg_Exam_Duration,
MIN(SEC_TO_TIME(TIMESTAMPDIFF(MINUTE, Start_Time, Finish_Time))) AS
Min_Exam_Duration,
MAX(SEC_TO_TIME(TIMESTAMPDIFF(MINUTE, Start_Time, Finish_Time))) AS
Max_Exam_Duration,
Room_ID FROM exam
GROUP BY Room_ID;
Desired output would correctly calculate the Max, Min, & Avg of the duration (time elapsed) between time in minutes
Current Output
Instead of:
TIMEDIFF(Finish_Time, Start_Time)
use:
SEC_TO_TIME(TIMESTAMPDIFF(SECOND, Start_Time, Finish_Time))
(Note the changed order of parameters.)

How to find records within a certain timeframe based on another field

How do I find all records 7 days before a field in an SQL database?
I need to find all transaction dates that were placed 7 days before the pickup date of the same record.
I am currently using SequelPro so that my have an effect on available syntaxes.
This is currently my table that I am pulling the records from.
This is the exact question I am being asked;
Write a query to display all details of transactions that were made at least one
week before the pickup date.
Isn't it straightforward?
SELECT * FROM TransactionTable
WHERE DATEDIFF(pickupdate, transactiondate) >= 7;

How to calculate data from different rows [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have following table to monitor the price each day, and I want to do calculation between two days like today's close price - previous day
s open price , e.g Thur's close - Wed's open, so I can see the difference.
Also, there is no records for the weekend, so how I can do 2 calculation different,
e.g 1. Mon's close - Sun returns same Mon price,
2. Mon's close price - previous Fri's open etc
INSERT INTO goods(date,day,open,high,low,close,`range(daily high- low)`) VALUES
('2018-11-01','Thu',1.08430,1.08766,1.08175,1.08285,0.00591),
('2018-11-02','Fri',1.08319,1.08585,1.07988,1.07988,0.00597),
('2018-11-05','Mon',1.08258,1.08389,1.08011,1.08155,0.00378),
('2018-11-06','Tue',1.08160,1.08489,1.07461,1.07469,0.01028),
('2018-11-07','Wed',1.07543,1.07646,1.07094,1.07150,0.00552),
('2018-11-08','Thu',1.07148,1.07571,1.07083,1.07393,0.00488),
('2018-11-09','Fri',1.07409,1.07651,1.07124,1.07125,0.00527),
('2018-11-12','Mon',1.07190,1.07389,1.06759,1.06878,0.00630),
('2018-11-13','Tue',1.06830,1.06977,1.06609,1.06658,0.00368)
Ideal output 1:
date, day, open, high, low,close, diff
('2018-11-01','Thu',1.08430,1.08766,1.08175,1.08285, ..
('2018-11-02','Fri',1.08319,1.08585,1.07988,1.07988, - 0.00442
('2018-11-05','Mon',1.08258,1.08389,1.08011,1.08155,- 0.00164
('2018-11-06','Tue',1.08160,1.08489,1.07461,1.07469,-0.00789
output 2:
date, day, open, high, low,close, diff
('2018-11-01','Thu',1.08430,1.08766,1.08175,1.08285, ..
('2018-11-02','Fri',1.08319,1.08585,1.07988,1.07988, - 0.00442
('2018-11-05','Mon',1.08258,1.08389,1.08011,1.08155, 1.08155
('2018-11-06','Tue',1.08160,1.08489,1.07461,1.07469,-0.00789
I am using php7.1, mysql
If you are using MySQL 8.0, you can use LAG() to access the immediate previous record, ordered by date. This will happily ignore gaps in days, so Monday closing price will be compared with Friday openning price :
SELECT
g.*,
g.close - LAG(g.open) OVER(ORDER BY g.date) price_diff
FROM goods g
Demo on DB Fiddle
With older versions of MySQL, one would typically use a self-join and a correlated subquery with a NOT EXISTS condition to retrieve the previous record :
SELECT g.*, g.close - g1.open price_diff
FROM goods g
LEFT JOIN goods g1
ON g1.date < g.date
AND NOT EXISTS (
SELECT 1 FROM goods g2 WHERE g2.date < g.date AND g2.date > g1.date
)
g is the current record (say : today). g1 represents yesterday’s record : to identify it, we indicate the RDBMS that :
g1's date is lower than g's date
no record (g2) exists with a date lower than today’s (g) and higher than yesterday’s (g1)
The combination of these two conditions allows the RDMS to uniquely identify the relevant record (yesterday’s), whose value can then be used in the computation.
Demo on DB Fiddle

mysql retrieve data from a range of time from table [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
-this is the table of picture i want to retrieve datas from
I need two queries.
the first one is to get the actionNo of the latest stopTime before the current time.
the second query is to get the actionNo if the latest actionTime before the current time.
Example:
If the current time was: 00:46:20
the first query is to get actionNo 9 (stoptime: 00:45:00)
the second query is to get actionNo 8 (actiontime: 00:41:30)
-this is eg of range to get data picture
SELECT MAX(id) FROM timestuff WHERE `actionTime` < CURTIME();
SELECT MAX(id) FROM timestuff WHERE `stopTime` < CURTIME();
This gets you the latest id of the action/stoptime before the current time, will work if your table always is in the order as you have shown (that means, ids display the chronology of your time values - which isn't the case in your data as I just noticed).
For your case: you can take another step and add a inner join on the time closest to the current time and then look up the id of that data.
First query: For the latest stopTime before the current time:
SELECT
timestuff.id
FROM
(
SELECT
MAX(stopTime) AS maxTime
FROM
timestuff
WHERE
`stopTime` < CURTIME()
) AS time
INNER JOIN timestuff ON timestuff.`stopTime` = time.maxTime;
Second query: For the first actionTime after the current time:
SELECT
timestuff.id
FROM
(
SELECT
MIN(actionTime) AS minTime
FROM
timestuff
WHERE
`actionTime` > CURTIME()
) AS time
INNER JOIN timestuff ON timestuff.`actionTime` = time.minTime;