MySQL Group By - Three tables with MIN function - mysql

I have searched on here to find an answer to my problem but to no avail.
I am working on a project where there are 3 tables involved, the 3 tables are flights, accommodation, and transfers.
The task is to find the cheapest price per month and per day so two separate queries.
The first query is to find the min price per month, an example:
SELECT
sub_a.startdate,
ROUND((
MIN(sub_a.aprice) +
MIN(sub_f.fprice) +
(SELECT MIN(t.PricePP) FROM matrix.iv_transfers AS t WHERE t.PropertyID = sub_a.PropertyID AND t.Adults = sub_a.adults AND t.Airport = sub_f.arrairport AND (sub_a.startdate BETWEEN t.RangeStart AND t.RangeEnd)) +
2.50
)) AS TotalPP,
ROUND(
(
MIN(sub_a.aprice) +
MIN(sub_f.fprice) +
(SELECT MIN(t.PricePP) FROM matrix.iv_transfers AS t WHERE t.PropertyID = sub_a.PropertyID AND t.Adults = sub_a.adults AND t.Airport = sub_f.arrairport AND (sub_a.startdate BETWEEN t.RangeStart AND t.RangeEnd)) +
2.50
) * 1.1
) AS TotalAgtPP,
sub_f.depairport,
sub_f.arrairport,
MONTH(sub_a.startdate) AS startdatet,
DATE_FORMAT(sub_a.startdate, "%b %y") AS FormatDate,
sub_a.duration,
sub_a.PropertyID
FROM (
SELECT
a.aid,
f.fid,
a.startdate,
f.outbounddate,
MIN(a.aprice) AS aprice,
MIN(f.fprice) AS fprice
FROM matrix.iv_liveaccomm AS a
JOIN matrix.iv_liveflights AS f USING (location, duration, adults)
WHERE a.PropertyID = 22
AND a.duration = 7
AND a.adults = 2
AND a.board = 'BB'
AND f.outbounddate = a.startdate
AND f.depairport = 'LHR'
GROUP BY a.aid, f.fid, a.startdate, f.outbounddate
) AS X
JOIN matrix.iv_liveaccomm AS sub_a ON(sub_a.aid = X.aid)
JOIN matrix.iv_liveflights AS sub_f ON(sub_f.fid = X.fid)
GROUP BY MONTH(X.startdate);
The query above returns the following result:
The 2nd query is to retrieve the min price per day for a given month.
SELECT
MONTH(sub_a.startdate) AS month_date,
ROUND((
sub_a.aprice +
sub_f.fprice +
(SELECT MIN(t.PricePP) FROM matrix.iv_transfers AS t WHERE t.PropertyID = sub_a.PropertyID AND t.Adults = sub_a.adults AND t.Airport = sub_f.arrairport AND (sub_a.startdate BETWEEN t.RangeStart AND t.RangeEnd)) +
2.50
)) AS TotalPP,
sub_f.depairport,
sub_f.arrairport,
MONTH(sub_a.startdate) AS startdatet,
DATE_FORMAT(sub_a.startdate, "%b %y") AS FormatDate,
sub_a.duration,
sub_a.PropertyID,
h.iv_PropertyReferenceID AS PropertyReferenceID,
sub_a.board,
sub_a.room,
sub_a.rating,
sub_a.`2for1`,
sub_a.`3for2`,
sub_a.`4for3`,
sub_a.`3and4`,
sub_a.freebb,
sub_a.adults,
sub_a.children,
sub_a.nss,
CONCAT("/search/results?tkn=",DATE_FORMAT(sub_a.startdate,"%d-%m-%Y"),"|",sub_a.duration,"|","A:",da.iv_AirportID,"|A:",aa.iv_AirportID,",R:",des.iv_RegionID,"|",r.iv_ResortID,"|",h.iv_PropertyReferenceID,"|",m.iv_MealBasisID,"|",sub_a.rating,"|1|",sub_a.adults,sub_a.children,",0|0,0,0|0,0,0|LPP|",sub_a.PropertyID) AS DeepLink
FROM (
SELECT
a.aid,
f.fid,
a.startdate,
f.outbounddate,
MIN(a.aprice) AS aprice,
MIN(f.fprice) AS fprice
FROM matrix.iv_liveaccomm AS a
JOIN matrix.iv_liveflights AS f USING (location, duration, adults)
WHERE a.PropertyID = 22
AND a.duration = 7
AND a.startdatet = 6
AND a.adults = 2
AND a.board = 'BB'
AND f.outbounddate = a.startdate
AND f.depairport = 'LHR'
GROUP BY a.aid, f.fid, a.startdate, f.outbounddate
) AS X
JOIN matrix.iv_liveaccomm AS sub_a ON(sub_a.aid = X.aid)
JOIN matrix.iv_liveflights AS sub_f ON(sub_f.fid = X.fid)
JOIN global.hotels AS h ON(h.iv_PropertyID = sub_a.PropertyID)
JOIN global.resorts AS r ON (r.iv_ResortID=h.iv_ResortID)
JOIN global.destinations AS des ON (des.iv_RegionID=r.iv_RegionID)
JOIN global.airports AS da ON (da.airportcode=sub_f.depairport)
JOIN global.mealbasis AS m ON (m.MealBasisCode=sub_a.board)
JOIN global.airports AS aa ON (aa.airportcode=sub_f.arrairport)
GROUP BY X.startdate;
and produces the following result:
As you can see from the first screenshot, the minimum price in June is 383 but in the 2nd screenshot, the minimum price is 386.
Why is the price different from grouping by month and date?
Thanks

Related

Convert mySQL partition query to mySQL 5.7 Compatible query where there are two sums in one query

I have the following query that works perfectly in mysql 8:
SELECT
J.JobID, Month(WH.DateStart) as MonthCharged, Year(WH.DateStart) as YearCharged, sum(WH.Duration) as HoursWorkedInMonth, sum(WH.Duration) over (partition by J.JobID order by Month(WH.DateStart), Year(WH.DateStart)) as CumulativeJobHoursWorked
FROM
tblJob J
JOIN tblTask T ON CONCAT('JOB-', RIGHT(YEAR(J.DateCreated), 2), '-', LPAD(J.JobID, 4, '0')) = T.SourceID
LEFT JOIN xrefTasktoEmployee XT ON T.TaskID = XT.TaskID
LEFT JOIN tblWorkHistory WH ON XT.WorkHistoryID = WH.WorkHistoryID
LEFT JOIN tblRates R ON XT.rateID = R.RateID
Where WH.Duration is not NULL
Group by J.JobID, Month(WH.DateStart), Year(WH.DateStart)
And it produces the following results:
Job ID
Month Charged
Year Charged
HoursWorkedInMonth
CumulativeJobHoursWorked
1
3
2021
23.98
23.98
1
4
2021
24.98
47.96
2
3
2021
8
8
3
2
2021
8
8
4
3
2021
1
1
5
2
2021
10
10
Notice how I am summing the hours worked in the month & year for a particular job, then I need the cumulative for that Job for the year.
I can't seem to figure out how to do this in MySQL 5.7 by using variables. Does anyone have any insights?
Thanks
Here is what I finally got to work:
SELECT
J.JobID, Month(WH.DateStart) as MonthCharged, Year(WH.DateStart) as YearCharged, sum(WH.Duration) as HoursWorkedInMonth, (SELECT
sum(WH2.Duration)
FROM
tblJob J2
JOIN tblTask T2 ON CONCAT('JOB-', RIGHT(YEAR(J2.DateCreated), 2), '-', LPAD(J2.JobID, 4, '0')) = T2.SourceID
LEFT JOIN xrefTasktoEmployee XT2 ON T2.TaskID = XT2.TaskID
LEFT JOIN tblWorkHistory WH2 ON XT2.WorkHistoryID = WH2.WorkHistoryID
Where WH2.Duration is not NULL and J2.JobID = J.JobID and DATE_FORMAT(WH2.DateStart, '%m-%Y') <= DATE_FORMAT(WH.DateStart, '%m-%Y')) as CumulativeJobHoursWorked
FROM
tblJob J
JOIN tblTask T ON CONCAT('JOB-', RIGHT(YEAR(J.DateCreated), 2), '-', LPAD(J.JobID, 4, '0')) = T.SourceID
LEFT JOIN xrefTasktoEmployee XT ON T.TaskID = XT.TaskID
LEFT JOIN tblWorkHistory WH ON XT.WorkHistoryID = WH.WorkHistoryID
Where WH.Duration is not NULL
Group by J.JobID, Month(WH.DateStart), Year(WH.DateStart)

Where do I put the sum function to sum sick leave days in this query?

The query shown below gives me the number of leave days excluding Saturday and Sunday. My problem is I don't know where to put the sum() function to sum all leave days.
SELECT DATEDIFF(eleave.resume_date , eleave.leave_date) as total_days , (
ABS(DATEDIFF(eleave.leave_date, eleave.resume_date)) -
ABS(DATEDIFF(ADDDATE(eleave.leave_date, INTERVAL 1 -
DAYOFWEEK(eleave.leave_date) DAY) , ADDDATE(eleave.resume_date, INTERVAL
1 - DAYOFWEEK(eleave.resume_date) DAY))) / 7 * 2 -
(DAYOFWEEK(IF(eleave.resume_date < eleave.leave_date , leave.resume_date,
eleave.leave_date)) = 1) - (DAYOFWEEK(IF(eleave.resume_date >
eleave.leave_date, eleave.resume_date, eleave.leave_date)) = 7)) as
leavedays , employee.emp_lname , type.typ_name as leavetype ,
education.qualification , education.program FROM employee INNER JOIN eleave on employee.emp_num = eleave.emp_num LEFT JOIN type ON type.typ_id =
eleave.typ_id left join education ON employee.emp_num = education.emp_num
WHERE employee.emp_num = 4774 AND type.typ_name = 'Sick leave'
You should do the sum per employee to get total leaves for each employee
it will look like this
SELECT employee.emp_num,
SUM (ABS(DATEDIFF(eleave.leave_date, eleave.resume_date)) - ABS(DATEDIFF(ADDDATE(eleave.leave_date, INTERVAL 1 - DAYOFWEEK(eleave.leave_date) DAY) , ADDDATE(eleave.resume_date, INTERVAL 1 - DAYOFWEEK(eleave.resume_date) DAY))) / 7 * 2 - (DAYOFWEEK(IF(eleave.resume_date < eleave.leave_date , leave.resume_date, eleave.leave_date)) = 1) - (DAYOFWEEK(IF(eleave.resume_date > eleave.leave_date, eleave.resume_date, eleave.leave_date)) = 7)) as leavedays
FROM employee INNER JOIN eleave on employee.emp_num = eleave.emp_num
LEFT JOIN type ON type.typ_id = eleave.typ_id left join education
ON employee.emp_num = education.emp_num
WHERE employee.emp_num = 4774 AND type.typ_name = 'Sick leave'
GROUP BY employee.emp_num

Expressing formula within a SELECT query

I have this existing query:
SELECT
extension
, Total_Outbound+Total_Missed+Total_Received AS Total_Calls
, Total_Missed
, Total_Talk_Time_minutes
FROM (
SELECT
, extension
, sum(if(Answered = 1,0,1)) AS Total_Missed
, sum(CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 1 ELSE 0 END) AS Total_Received
, sum(if(LEGTYPE1 = 1,1,0)) AS Total_Outbound
, round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes
FROM session a
GROUP BY extension
) x;
It works great but I need to add a metric/formula to it called missed_call_score right under Total_Talk_Time_Minutes.
The formula for the missed call score is this:
(missed calls/total talk time) * (average calls per CSR/total calls) * 100 but one thing to note is that the average calls per csr needs to ignore the MAX and MIN, so the lowest and highest number of calls taken.
I'm not sure how I could construct this score within a single select variable or the syntax I would use for this given the fact that it has to throw out the max and min.
Here is an example of my needed output and the formulas it should be using:
extension | Total calls | missed calls | total talk time | missed call score
----------------------------------------------------------------------------
1234 8 4 15.5 5.7
4321 4 0 9.42 0.0
5678 5 2 6.78 6.5
9876 13 6 18.3 7.2
Total call sum = 30
Total call sum without high and low = 13
average calls per CSR = (13/2) = 6.5
extension 1 = (4/15.5) * (6.5/30) * 100 = 5.7
extension 2 = (0/9.42) * (6.5/30) * 100 = 0.0
extension 3 = (2/6.78) * (6.5/30) * 100 = 6.5
extension 4 = (6/18.3) * (6.5/30) * 100 = 7.2
The data above for extension, total calls, missed calls and talk time are taken from my sql fiddle, linked below. I simply added the score column to give example of my expected output.
The fiddle linked below shows my create and inserts so hopefully that gives everything needed to assist me with this.
**sql fiddle
**
http://sqlfiddle.com/#!9/aa1f9/1
UPDATE
Full production query with joins
SELECT firstn ,
lastn ,
extension ,
Total_Outbound+Total_Missed+Total_Received AS Total_Calls ,
Total_Missed ,
Total_Talk_Time_minutes ,
Total_All_Calls ,
Max_Calls ,
Min_Calls ,
CSR_Count ,
((Total_Missed/Total_Talk_Time_minutes) *
(((Total_All_Calls-Max_Calls-Min_Calls)/CSR_Count)/Total_All_Calls)) * 100
FROM ( SELECT u.firstn ,
u.lastn ,
c.extension ,
sum(if(Answered = 1,0,1)) AS Total_Missed ,
sum(CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 1 ELSE 0 END) AS Total_Received ,
sum(CASE WHEN LEGTYPE1 = 1 THEN 1 ELSE 0 END) AS Total_Outbound ,
round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes ,
(SELECT COUNT(1) FROM ambition.session a INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)) Total_All_Calls ,
(SELECT MAX(CNT) FROM (SELECT COUNT(1) CNT, c.extension
FROM ambition.SESSION a INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312) GROUP BY responsibleuserextensionid) y) Max_Calls ,
(SELECT MIN(CNT) FROM (SELECT COUNT(1) CNT, c.extension
FROM ambition.SESSION a
INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)GROUP BY responsibleuserextensionid) y) Min_Calls ,
(SELECT COUNT(DISTINCT c.extension)-2
FROM ambition.SESSION a INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)) CSR_Count
FROM ambition.session a
INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
INNER join jackson_id.users u ON c.extension = u.extension
LEFT JOIN ambition.knownnumbers k ON a.callingpartyno = k.phone_number
WHERE b.ts between curdate() - interval 5 day and now()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
GROUP BY c.extension, u.firstn, u.lastn ) x
This should work for you:
SELECT
extension
, Total_Outbound+Total_Missed+Total_Received AS Total_Calls
, Total_Missed
, Total_Talk_Time_minutes
, Total_All_Calls
, Max_Calls
, Min_Calls
, CSR_Count
, ((Total_Missed/Total_Talk_Time_minutes) *
(((Total_All_Calls-Max_Calls-Min_Calls)/CSR_Count)/Total_All_Calls)) * 100
FROM (
SELECT
extension
, sum(if(Answered = 1,0,1)) AS Total_Missed
, sum(CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 1 ELSE 0 END) AS Total_Received
, sum(CASE WHEN ANSWERED = 1 AND LEGTYPE1 = 1 THEN 1 ELSE 0 END) AS Total_Outbound
, round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes
, (SELECT COUNT(1) FROM session) Total_All_Calls
, (SELECT MAX(CNT) FROM (SELECT COUNT(1) CNT, EXTENSION FROM SESSION GROUP BY EXTENSION) y) Max_Calls
, (SELECT MIN(CNT) FROM (SELECT COUNT(1) CNT, EXTENSION FROM SESSION GROUP BY EXTENSION) y) Min_Calls
, (SELECT COUNT(DISTINCT EXTENSION)-2 FROM SESSION) CSR_Count
FROM session a
GROUP BY extension
) x;
Here is the fiddle.
Basically I used sub-counts in your derived table x to get each of the variables needed for missed_call_score. One major thing worth noting is that the logic was off for Total_Outbound, so I tweaked that to a CASE statement instead of an IF(). I selected the count columns in the outer query just so you can see what is going on, you can remove those.
I've done something similar in the past and extracted this snippet from my code.
I think/hope that this might help you getting started (I left out most of the columns from your query and you'd have to adjust avg(amount) to match your formula.
select extension, avg(amount) from
(
select t.*,
min(amount) over (partition by extension) as min_amt,
max(amount) over (partition by extension) as max_amt
from your_table t
) t
where amount > min_amt and amount < max_amt group by extension;

sql query with DISTINCT make huge performance issue

i have a query to get summary of donations
SELECT CONVERT(CHAR(2), CAST(pb.PayrollDate AS DATETIME), 101)
+ '/' + CONVERT(CHAR(4), CAST(pb.PayrollDate AS DATETIME), 120) AS Closing_Month ,
CONVERT(CHAR(6), CAST(pb.PayrollDate AS DATETIME), 112) AS Closing_Year ,
COUNT(DISTINCT Donation.Employee) + ( SELECT COUNT(*)
FROM dbo.Donation
INNER JOIN PayrollBatch pbd ON Donation.PayrollBatch = pbd.ID
WHERE CONVERT(CHAR(6), CAST(pbd.PayrollDate AS DATETIME), 112) = CONVERT(CHAR(6), CAST(pb.PayrollDate AS DATETIME), 112)
AND DonationType = 5
)AS 'Donors' ,
COUNT (DISTINCT( CASE WHEN Donation.DonationType = 1 OR Donation.DonationType = 5 THEN CharityDetails.ID
END ))AS 'Charities',
( CAST(COUNT(DISTINCT Donation.Employee) AS DECIMAL(18, 2))
/ ( SELECT SUM(NumberOfEmployees)
FROM OrganisationDetail
WHERE ID = Donation.OrganisationDetail
AND IsDeleted = 0
) ) * 100 AS 'Participation_Rate' ,
SUM(CASE WHEN Donation.DonationType = 1 OR Donation.DonationType = 5 THEN Donation.Amount
ELSE 0
END) AS 'Employee_Donations' ,
SUM(CASE WHEN Donation.DonationType = 2 THEN Donation.Amount
ELSE 0
END) AS 'Matched_Donations' ,
SUM(CASE WHEN Donation.DonationType = 1
OR Donation.DonationType = 2 OR Donation.DonationType = 5 THEN Donation.Amount
ELSE 0
END) AS 'Total_Donations'
FROM Donation
INNER JOIN OrganisationDetail AS OrganisationDetail_1 ON Donation.OrganisationDetail = OrganisationDetail_1.ID
INNER JOIN CharityProjectDetails ON Donation.CharityProjectDetails = CharityProjectDetails.ID
INNER JOIN CharityDetails ON CharityProjectDetails.CharityDetails = CharityDetails.ID
INNER JOIN PayrollBatch pb ON Donation.PayrollBatch = pb.ID
LEFT JOIN Employee ON Donation.Employee = Employee.ID
LEFT JOIN DonationIntent ON Donation.DonationIntent = DonationIntent.ID
LEFT JOIN EmployeeAddress ON Employee.ID = EmployeeAddress.Employee
LEFT JOIN dbo.PayrollBatchOther pbo ON pbo.PayrollBatch = pb.ID
GROUP BY CONVERT(CHAR(2), CAST(pb.PayrollDate AS DATETIME), 101)
+ '/' + CONVERT(CHAR(4), CAST(pb.PayrollDate AS DATETIME), 120) ,
CONVERT(CHAR(6), CAST(pb.PayrollDate AS DATETIME), 112) ,
Donation.OrganisationDetail
ORDER BY Closing_Year;
i need to get unique donors count from result set COUNT(DISTINCT e.ID) but with distinct query takes 7-9 sec to complete execution but without that it took only 1 sec how to improve that performance
Update
Here is the Paste The Plan

MYSQL | Get two different records from single table

Ok. This is kind of complicated.. I have been trying to achieve it and got no where so far.
I have three tables.
leave_approval
leave_applications
ml_leave_type
Here is leave_approval Table
which is then linked to leave_application from leave_application_id
Now here comes the Tricky Question,
i want two records from table.
I want Total leaves taken by employee in year 2014
I want Total Leaves taken by employee in month november of 2014
so means need two columns with two different approaches yearly and monthly.
i have query so far.
SELECT
LA.employee_id,
DATEDIFF(
LA.approved_to,
LA.approved_from
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE YEAR(LA.approval_date) = 2014
AND LA.`employee_id` = 1
and here is the result i am getting for the query..
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
UPDATE
May i could not clearly explain my problem.
What i am trying to achieve is add two extra columns not remove the columns i have. i mean i am using most/All of the select fields i have
Plus i want the Total Leaves in Year 2014 in one column and Total Leaves in the month in different field for that given year.
so here is kind of example i want.>
ml_leave_type_id | Total Leaves Taken in Year (e-g 2014) | Total Leaves taken in Month (e-g November)
1 10 2
2 6 0
3 4 1
Would something like that do?
Total leaves for employee_id = 1, Year 2014
SELECT
LA.employee_id,
SUM(
DATEDIFF(
LA.approved_to,
LA.approved_from
)
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE YEAR(LA.approval_date) = 2014
AND LA.`employee_id` = 1
GROUP BY LA.`employee_id` = 1
Total leaves for employee_id = 1, Year = 2014 AND Month = 11
SELECT
LA.employee_id,
SUM(
DATEDIFF(
LA.approved_to,
LA.approved_from
)
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE YEAR(LA.approval_date) = 2014
AND MONTH(LA.approval_date) = 11
AND LA.`employee_id` = 1
GROUP BY LA.`employee_id` = 1
I do notice in your dataset however that there are some dates that are ovelapping. For example:
employee_id = 1 is on leave 2014/11/01 - 2014/11/06 AND 2014/11/05 - 2014/11/08. What's the deal with the dates 2014/11/05 and 2014/11/06. How will the system handle this scenario
Edit2: updated select statement after requirements clarified. The update consist of reorganizing with using a JOIN instead of UNION ALL
select a.*, b.*
from (
SELECT
LA.employee_id,
DATEDIFF(
LA.approved_to,
LA.approved_from
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE YEAR(LA.approval_date) = 2014
AND LA.`employee_id` = 1
) a
JOIN (
SELECT
LA.employee_id,
DATEDIFF(
LA.approved_to,
LA.approved_from
) AS TotalLeavesTaken,
LAPP.`entitlement_id`,
LAPP.`ml_leave_type_id`,
LA.leave_application_id,
LA.approved_from AS LeaveFrom,
LA.approved_to AS LeaveTo
FROM
leave_approval LA
INNER JOIN leave_application LAPP
ON LAPP.application_id = LA.leave_application_id
WHERE MONTHNAME(LA.approval_date) = 'November'
AND LA.`employee_id` = 1
) b
ON a.employee_id = b.employee_id