I have to generate a report using 4 tables, I tried a lot of joins, but I get wrong values 🙁
Hope someone will help me.
StaffAssign Table:
----------------------------
| Tid | StaffId | Planned |
----------------------------
| 123 | 2 | 10:00:00 |
| 123 | 4 | 05:00:00 |
| 124 | 2 | 09:00:00 |
----------------------------
ActualEffort Table:
--------------------------------------------
| Tid | StaffId | ActualEffort | logdate |
--------------------------------------------
| 123 | 2 | 05:00:00 |2012-09-01|
| 123 | 4 | 05:00:00 |2012-09-01|
| 123 | 2 | 06:00:00 |2012-09-03|
| 124 | 2 | 09:00:00 |2012-09-04|
--------------------------------------------
ProjectList Table:
-------------------
| ProjectId | Tid |
-------------------
| 1 | 123 |
| 2 | 124 |
-------------------
ProjectName Table:
-------------------
| Id | name |
-------------------
| 1 | project1 |
| 2 | project2 |
-------------------
Below is the Query I’m using:
SELECT P.id AS projectid,P.name,
SEC_TO_TIME(SUM(TIME_TO_SEC(A.planned)))planned,SEC_TO_TIME(SUM(TIME_TO_SEC(E.actualeffort)))actual FROM actualeffort E
INNER JOIN staffassign A ON A.tid = E.tid
INNER JOIN projectlist L ON L.tid = A.tid
INNER JOIN projectname P ON P.id = L.projectid
WHERE E.logdate BETWEEN FROM_UNIXTIME('1346475600') AND FROM_UNIXTIME('1348290000')
GROUP BY P.id
I’m getting this:
---------------------------------------------
| projectid | name | planned | actual |
---------------------------------------------
| 1 | project1 | 15:00:00| 12:00:00 |
| 2 | project2 | 09:00:00| 09:00:00 |
---------------------------------------------
But it should be like:
---------------------------------------------
| projectid | name | planned | actual |
---------------------------------------------
| 1 | project1 | 15:00:00| 16:00:00 |
| 2 | project2 | 09:00:00| 09:00:00 |
---------------------------------------------
I’m very confused that, I don’t know where I’m going wrong with the joins.
Someone please help me, I’m struck with this.
The WHERE filter may be wrong. Note that first datetime in the condition starts at ’08:00:00′ –
The type of
ActualEffort.logdatefield is DATE; the value ‘2012-09-01’ is less then ‘2012-09-01 08:00:00’. So change this condition or use DATE function –(edited)
For one thing, when you join
StaffAssignandActualEfforton theTidcolumn only, you get a mini-Cartesian product forTid=123in particular, because both tables contain more than one row with thatTidand there’s no other specific condition to establish a 1:1 or, at most, 1:N relationship between the rows.But in fact, 1:N wouldn’t do either: although it wouldn’t give you the Cartesian product effect, it would result in duplicated values on one side and, as a consequence, in a distorted SUM.
Therefore, data in
StaffAssignand those inActualEffortmust be aggregated separately, then joined, something like this: