简体   繁体   中英

SUM in Inner/Left/Right Joins on SQL Query

I have three tables on my mySQl database which are:

Employee :

ID int
Name
Surname

DayOffRequest :

ID int (PK)
EmployeeID FK references Employee
HowManyDays double

Rank :

ID int (PK)
EmployeeID FK references Employee
daysEmployeeCanGet double

Every employee has ranks and how many days off he can get per year is specified by his rank. For example on the first year he can get 14 days at total. Their days of are being held by DaysOffRequest .

I'd like to get UserID, RankID, SUM(HowManyDays), SUM(daysEmplooyeeCanGet) in one query.

I used

SELECT 
    e.id, r.id,
    SUM(r.daysEmployeeCanGet),
    SUM(HowManyDays) 
FROM 
    Employee e 
INNER JOIN 
    Rank r ON r.`userID` = e.`ID` 
INNER JOIN 
    DayOffRequest 

But it didn't work. I mean It did work but not as wanted.

I actually want to make a query like whenever an employee gets a day off it automatically reduce the number of days he gets from the total days that he can get.(total days that he can get is sum of daysEmployeeCanGet for everyrank he has.)

How can I achieve that goal?

I hope I am clear enough.

Thank you.

Try below query, but there must be one row in Rank table for each employee because I have used max.

SELECT u.id
       MAX(r.daysEmployeeCanGet) 'Allowed',
       SUM(HowManyDays) 'Availed',
       MAX(r.daysEmployeeCanGet) - SUM(HowManyDays) 'Remaining'
FROM User u
INNER JOIN Rank r ON r.EmployeeID=u.ID
INNER JOIN DayOffRequest dor ON u.ID = dor.EmployeeID
GROUP BY u.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM