Employee available for task between a date range - mysql

I have been working on a employee work management project and I am a little stuck. I have 3 tables:
1: employees
empid, empFirst empLast
1 jon smith
2 mark road
3 jane hall
2: holiday
id employee id datestart dateend
1 2 2015-08-07 2015-08-12
2 3 2015-07-4 2015-07-11
3 2 2015-07-20 2015-07-24
3: Task Assigned
id taskid assignedTo(userid) startTask endTask
1 1 1 2015-07-10 2015-07-14
2 2 2 2015-07-29 2015-07-29
3 2 3 2015-07-18 2015-07-30
4 3 2 2015-08-30 2015-09-03
5 4 2 2015-09-10 2015-09-03
I'm not sure how to go about querying the tables to see who is available for a task in a date range (multiple user assigned to the same task). I have a query which I would here:
so if you take the holiday table out if the equation and just run the query below
SELECT employees.empId, employees.empFirst, employees.empLast
FROM employees
LEFT JOIN taskassigned
ON employees.empId = taskassigned.assignedTo
WHERE taskassigned.assignedTo IS NULL or
not (taskassigned.startTask BETWEEN '2015-07-29 14:30:00' AND '2015-07-29 18:30:00'
or taskassigned.endTask BETWEEN '2015-07-29 14:30:00' AND '2015-07-29 18:30:00')
the result I get is:
empId empFirst empLast
1 jon smith (he is available)
2 mark road
2 mark road
As you can see Mark is not available on this date (in the task table).
I would like the query the holiday table first to see if they are on holiday then the task table to see if they already have a task on the date range then the result to show me how is available for the task.

I can't test this at the moment, but try:
SELECT employees.empId, employees.empFirst, employees.empLast
FROM employees
LEFT JOIN taskassigned
ON employees.empId = taskassigned.assignedTo
LEFT JOIN holiday
ON employees.empId = holiday.employeeId
WHERE (
taskassigned.assignedTo IS NULL
OR (
'2015-07-29 14:30:00' NOT BETWEEN taskassigned.startTask AND taskassigned.endTask
AND '2015-07-29 18:30:00' NOT BETWEEN taskassigned.startTask AND taskassigned.endTask
)
)
AND (
holiday.employeeId IS NULL
OR (
'2015-07-29 14:30:00' NOT BETWEEN holiday.dateStart AND holiday.dateEnd
AND '2015-07-29 18:30:00' NOT BETWEEN holiday.dateStart AND holiday.dateEnd
)
)
This would check to see if the specified start date doesn't fall inbetween the assigned task's start or end date, and if the specified end date doesn't fall inbetween the assigned task's start or end date, and then do the same for holidays.

Hi I don't have the right tools to test right now but here is what you can try to do:
when using date comparison:
try to convert/cast to DATE (make sure time is not included) to make sure the result is correct.
as far as I know when using between the start and end date are also included (maybe in some RDMS feature)
Also for including holiday, what you can do is like this (either):
first join with holiday table first then with the result join again with the task assigned table.
or
first join with task assigned table then with the result join again with the holiday table
Sorry for no code included, as I have no time to setup.

Related

Combining between two tables in MySQL and getting the distinct answer

I know this has probably been asked before but I am trying to find the correct way to this and I have been struggling for the past week or so.
So we have two sets of data for example, one table is called 'Order Log' and another is called 'Customer Information'
and here are example of the two data set
NOTE: The order log will sometimes have order from the same customer twice
Order Log Table
Customer ID
Date
Order Number
Order Amount
sgcwi
2022-06-11
124
3
gbtfc
2022-07-09
12
4
crownwood
2022-04-08
123
1
kcsi
2022-02-24
543
1
ulsteri
2022-08-08
423
2
gbtfc
2022-07-08
1254
3
ulsteri
2022-04-08
345
2
kcsi
2022-07-13
64
1
crownwood
2022-07-04
55
1
Customer Information Table
Customer Name
Customer ID
Contact
Sagen Private
sgcwi
email
Granten Viel
gbtfc
phone
Crownwood LTD
crownwood
email
Kings College
kcsi
email
Ulster FC
ulsteri
phone
So what my question is, how do i write an sql query that gives me back the the last order for each customer from the Order Log table withhin a span of the last 6 Months and returns me back the customer name for each of those selected data from the customer Informationt table. like such
The Sql Query Return that i want
Customer Name
Customer ID
Date
Sagen Private
sgcwi
2022-06-11
Granten Viel
gbtfc
2022-06-11
Crownwood LTD
crownwood
2022-07-04
Kings College
kcsi
2022-07-13
Ulster FC
ulsteri
2022-08-08
so far I have figured out to get the result from the Log table that I gave to use the query
"SELECT DISTINCT orderLog.customerID FROM Order WHERE qslogv2.date >= DATE_ADD(NOW(), INTERVAL -3 MONTH);
But I am yet to figure out how do i connect the Customer Information table to this query so it returns me the appropriate customer name along with the query.
I tried using the above query that I mentioned and also tried the UNION keyword in MySQL but to my demise I was not able to get to a point where I got that desired result.
Use JOIN-statement combined with MAX + GROUP BY.
In JOIN you tell what columns match in the joined tables. In your case it is the Customer ID.
With GROUP BY, you divide the rows into sets (based on the customer) and then applies the MAX-function for each of those sets, so that you will get the latest date for each customer.
select
c.name,
c.id,
max(ol.date)
from customerInformation c
join orderLog ol on ol.customerID=c.id
where ol.date between date_sub(now(), interval 6 month) and now()
group by c.name, c.id

Calculate total scheduled against total actual in two separate tables

I have two tables in my schema. The first contains a list of recurring appointments - default_appointments. The second table is actual_appointments - these can be generated from the defaults or individually created so not linked to any default entry.
Example:
default_appointments
id
day_of_week
user_id
appointment_start_time
appointment_end_time
1
1
1
10:00:00
16:00:00
2
4
1
11:30:00
17:30:00
3
6
5
09:00:00
17:00:00
actual_appointments
id
default_appointment_id
user_id
appointment_start
appointment_end
1
1
1
2021-09-13 10:00:00
2021-09-13 16:00:00
2
NULL
1
2021-09-13 11:30:00
2021-09-13 13:30:00
3
6
5
2021-09-18 09:00:00
2021-09-18 17:00:00
I'm looking to calculate the total minutes that were scheduled in against the total that were actually created/generated. So ultimately I'd end up with a query result with this data:
user_id
appointment_date
total_planned_minutes
total_actual_minutes
1
2021-09-13
360
480
1
2021-09-16
360
0
5
2021-09-18
480
480
What would be the best approach here? Hopefully the above makes sense.
Edit
OK so the default_appointments table contains all appointments that are "standard" and are automatically generated. These are what appointments "should" happen every week. So e.g. ID 1, this appointment should occur between 10am and 4pm every Monday. ID 2 should occur between 11:30am an 5:30pm every Thursday.
The actual_appointments table contains a list of all of the appointments which did actually occur. Basically what happens is a default_appointment will automatically generate itself an instance in the actual_appointments table when initially set up. The corresponding default_appointment_id indicates that it links to a default and has not been changed - therefore the times on both will remain the same. The user is free to change these appointments that have been generated by a default, resulting in setting the default_appointment_id to NULL * - or -* can add new appointments unrelated to a default.
So, if on a Monday (day_of_week = 1) I should normally have a default appointment at 10am - 4pm, the total minutes I should have planned based on the defaults are 360 minutes, regardless of what's in the actual_appointments table, I should be planned for those 360 minutes every Monday without fail. If in the system I say - well actually, I didn't have an appointment from 10am - 4pm and instead change it to 10am - 2pm, actual_appointments table will then contain the actual time for the day, and the actual minutes appointed would be 240 minutes.
What I need is to group each of these by the date and user to understand how much time the user had planned for appointments in the default_appointments table vs how much they actually appointed.
Adjusted based on new detail in the question.
Note: I used day_of_week values compatible with default MySQL behavior, where Monday = 2.
The first CTE term (args) provides the search parameters, start date and number of days. The second CTE term (drange) calculates the dates in the range to allow generation of the scheduled appointments within that range.
allrows combines the scheduled and actual appointments via UNION to prepare for aggregation. There are other ways to set this up.
Finally, we aggregate the results per user_id and date.
The test case:
Working Test Case (Updated)
WITH RECURSIVE args (startdate, days) AS (
SELECT DATE('2021-09-13'), 7
)
, drange (adate, days) AS (
SELECT startdate, days-1 FROM args UNION ALL
SELECT adate + INTERVAL '1' DAY, days-1 FROM drange WHERE days > 0
)
, allrows AS (
SELECT da.user_id
, dr.adate
, ROUND(TIME_TO_SEC(TIMEDIFF(da.appointment_end_time, da.appointment_start_time))/60, 0) AS planned
, 0 AS actual
FROM drange AS dr
JOIN default_appointments AS da
ON da.day_of_week = dayofweek(adate)
UNION
SELECT user_id
, DATE(appointment_start) AS xdate
, 0 AS planned
, TIMESTAMPDIFF(MINUTE, appointment_start, appointment_end)
FROM drange AS dr
JOIN actual_appointments aa
ON DATE(appointment_start) = dr.adate
)
SELECT user_id, adate
, SUM(planned) AS planned
, SUM(actual) AS actual
FROM allrows
GROUP BY adate, user_id
;
Result:
+---------+------------+---------+--------+
| user_id | adate | planned | actual |
+---------+------------+---------+--------+
| 1 | 2021-09-13 | 360 | 480 |
| 1 | 2021-09-16 | 360 | 0 |
| 5 | 2021-09-18 | 480 | 480 |
+---------+------------+---------+--------+

Converting the result of a MySQL table as per requirement

The mysql table we work on has data in the following format:
entityId status updated_date
-------------------------------
1 1 29/05/2017 12:00
1 2 29/05/2017 03:00
1 3 29/05/2017 07:00
1 4 29/05/2017 14:00
1 5 30/05/2017 02:00
1 6 30/05/2017 08:00
2 1 31/05/2017 03:00
2 2 31/05/2017 05:00
.
.
So every entity id has 6 statuses, and every status has an update datetime. Each status has an activity attached to it.
For example 1 - Started journey
2 - Reached first destination
3 - Left Point A, moving towards B. etc
I need to get an output in the below format for specific entity id eg 3 and 4. I need the time for status 3 and 4 independently.
entity_id time_started_journey time_reached_first_destination
(update time of status 3) (update time of status 4)
--------------------------------------------------------------
1 29/05/2017 7:00 29/05/2017 14:00
2 30/05/2017 7:00 30/05/2017 16:00
Later I need to calculate the total time which would be the difference of the two.
How can I achieve the desired result using mysql.
I tried using Union operator but cannot do it separate columns.
Also, tried using case when operator with the below query but failed.
select distinct entityid,
(case status when 3 then freight_update_time else 0 end)
as starttime,
(case status when 4 then freight_update_time else 0 end) as endtime
from table ;
Can anyone throw light on this?
Conditional aggregation is one way to return a resultset that looks like that.
SELECT t.entityid
, MAX(IF(t.status=3,t.updated_date,NULL)) AS time_started_journey
, MAX(IF(t.status-4,t.updated_date,NULL)) AS time_reached_first_destination
FROM mytable t
WHERE t.status IN (3,4)
GROUP BY t.entityid
ORDER BY t.entityid
This is just one suggestion; the specification is unclear about what the query should do with duplicated status values for a given entityid.
There are other query patterns that will return similar results.
My query in MySQL
SELECT
e3.updated_date AS sta3,
e4.updated_date AS sta4
FROM
`prueba` AS e3
LEFT JOIN prueba AS e4
ON
e3.entityId = e4.entityId AND e4.status = 4
WHERE
e3.status = 3
OUTPUT:

SQL: how select all rows where a "count > 1" for certain fields

I have 1 table, that has records by date. I need to compare data from year 1 to year 2 (last year), but in some cases a few records in year 1 don't exist in year 2 and some in year 2 do not exist in year 1.
I only care about those that match. my structure is:
F_DATE F_TEXT1 F_TEXT2 F_NUMBER1 F_NUMBER2
2014-01-01 bob sue 19 12
2013-04-19 bob sue 12 11
2013-06-01 bob jane 5 6
2014-11-28 jane bob 4 4
2014-03-12 mike bob 8 1
so in the above example only care about the records that contain bob + sue.
I can identify records by concat(F_TEXT1,F_TEXT2) as f_compare to get bobsue i can then count on this field having count(*) > 1 but doing this doesn't work well because F_DATE is unique to the pairing, and F_NUMBER1 and F_NUMBER2 are fundamental for further processing.
I am joining to another table, which has a F_LABEL for the years and a Start Date (F_SDATE) and End Date (F_EDATE) column to provide a nice label for the years.
I am having difficulty getting my records into a query so i can the process them further.
I have tried to select everything i need - this query gives the extra records from year 1 and year 2. and i also select a F_DATE from T_SOMETABLE which is basically for config so this query can be updated to compare year 3 to 4 etc by changing F_SOMEVALUE.
SELECT F_LABEL, F_TEXT1, F_TEXT2, F_NUMBER1, F_NUMBER2, fix
FROM (
SELECT b.F_LABEL, a.F_TEXT1, a.F_TEXT2, a.F_HGOALS, a.F_AGOALS,
concat(F_HOME,'-',F_AWAY) as fix FROM all_records a, some_labels b
WHERE a.F_DATE > b.F_SDATE
AND a.F_DATE < b.F_EDATE
AND a.F_DATE > (SELECT F_DATE FROM T_SOMETABLE WHERE F_SOMEVALUE='1')
UNION ALL
SELECT F_LABEL, F_TEXT1, F_TEXT2, F_NUMBER1, F_NUMBER2,
concat(F_TEXT1,'-',F_AWAY) as fix
FROM all_records a, some_labels b
WHERE a.F_DATE > b.F_SDATE
AND a.F_DATE < b.F_EDATE
AND a.F_DATE > (SELECT F_DATE FROM T_SOMETABLE WHERE F_SOMEVALUE='2')
AND a.F_DATE < (SELECT F_DATE FROM T_SOMETABLE WHERE F_SOMEVALUE='1')
) z
ORDER BY F_TEXT1, F_TEXT2, F_LABEL
I can't get my head round select from year 2 where the concat (above) exists in year 1 and then selecting the F_LABEL, F_TEXT1, F_TEXT2, F_NUMBER1 and F_NUMBER2from both years into one table.
Can you help point me in the right direction?
Bonus points if this query can go into a VIEW (nested statements don't help here) so the query/table doesn't need to be recreated every time a new record is added.
The query needs to be perform well as the output would appear on a webpage.
It is difficult to give a precise answer but, in order to compare a year with the previous one, you need to join your table with itself (t1 and t2 below are two occurrences of yourtable), to form a query like this:
SELECT ...
FROM yourtable t1, yourtable t2
WHERE (t1.F_TEXT1 = t2.F_TEXT1
OR t1.F_TEXT2 = t2.F_TEXT2)
AND YEAR(t1.F_DATE) = YEAR(t2.F_DATE) - 1

Finding dates within one year of each other

I am trying to determine the number of employees who left the company within 1 year of being hired:
SELECT
Min(O896IA_VEMPPRSA.EMP_RHR_DT) AS MinOfEMP_RHR_DT,
Max(O867IA_VJOBHST.REC_EFF_STT_DT) AS MaxOfREC_EFF_STT_DT,
O896IA_VEMPPRSA.SYS_EMP_ID_NR
FROM O896IA_VEMPPRSA
INNER JOIN O867IA_VJOBHST
ON O896IA_VEMPPRSA.SYS_EMP_ID_NR = O867IA_VJOBHST.SYS_EMP_ID_NR
WHERE
O867IA_VJOBHST.EMP_ACN_TYP_CD="TER"
GROUP BY
O896IA_VEMPPRSA.SYS_EMP_ID_NR;
EMP_RHR_DT is the original hire date, and REC_EFF_STT_DT is the date they quit/were fired. Again I need the REC_EFF_STT_DT to be within 365 days of the EMP_RHR_DT. Any thoughts?
Example of RHR Date Changes. IN some cases there will only be one job but still a negative days worked, in other cases it is because it is selecting the wrong job.
Job MinOfEMP_RHR_DT MaxOfREC_EFF_STT_DT daysworked SYS_EMP_ID_NR
abc1 10/24/2012 4/15/2013 173 123456
abc1 4/25/2013 4/13/2013 -12 234567
abc3 7/8/2013 1/4/2013 -185 891234
abc4 7/8/2013 7/29/2013 21 891234
Assuming O896IA_VEMPPRSA is master table and O867IA_VJOBHST is detail table with the following data:
O896IA_VEMPPRSA:
ID EMP_RHR_DT SYS_EMP_ID_NR Empname
1 8/10/2012 1 John
2 10/10/2012 2 Matthew
O867IA_VJOBHST:
ID SYS_EMP_ID_NR EMP_ACN_TYP_CD REC_EFF_STT_DT
1 1 Married 1/1/2003
2 1 Became dad 8/1/2003
3 1 TER 9/10/2013
5 2 Remarried 1/1/2003
6 2 Remarried 8/1/2003
7 2 TER 9/10/2013
You could do this to get the number of days worked:
SELECT
Min(O896IA_VEMPPRSA.EMP_RHR_DT) AS MinOfEMP_RHR_DT,
Max(O867IA_VJOBHST.REC_EFF_STT_DT) AS MaxOfREC_EFF_STT_DT,
Max(O867IA_VJOBHST.REC_EFF_STT_DT) - Min(O896IA_VEMPPRSA.EMP_RHR_DT) as daysworked,
O896IA_VEMPPRSA.SYS_EMP_ID_NR
FROM O896IA_VEMPPRSA
INNER JOIN O867IA_VJOBHST
ON O896IA_VEMPPRSA.SYS_EMP_ID_NR = O867IA_VJOBHST.SYS_EMP_ID_NR
WHERE
O867IA_VJOBHST.EMP_ACN_TYP_CD="TER"
GROUP BY
O896IA_VEMPPRSA.SYS_EMP_ID_NR;
HAVING
(Max(O867IA_VJOBHST.REC_EFF_STT_DT) - Min(O896IA_VEMPPRSA.EMP_RHR_DT)) < 365;
The solution is with the datediff function. You will end up with a constraint like:
WHERE DateDiff("yyyy",hiringDate, endingDate)<1
Please check the exact syntax for the DateDiff function in the MS-Access help