in MySql database I have to make some little tricky query.
I must get result only in TWO COLUMNS (TYPE (PROJECT,SUPPORT,EDUCATION) and VALUE (60 and 40 on example))
I have static table which contains types:
T1
ID TYPE
1 PROJECT
2 PROJECT
3 PROJECT
4 SUPPORT
5 EDUCATION
I have static table T2 with all tasks that has value of some of the type:
T2
TASK T1ID
1 1
2 1
3 2
4 3
5 4
6 5
T3 is DYNAMIC table of created tasks with some IDS.
T3
ID
1
2
3
4
5
6
T4 table has information who created those tasks.
T4
T3ID Name
1 Bob Marley
2 Bob Marley
3 Bob Marley
4 Bob Marley
5 Tom Cruise
6 Bob Marley
and finally T5 contains info from T2 and T3
T5
TASK T3ID
1 1
2 2
3 3
5 4
1 5
5 6
For some specific person (always one person- in this example Bob Marley or Tom Cruise)
I must haave statistics in PERCENTAGE how many they worked on PROJECTS or SUPPORT or EDUCATION.
So I will select Bob Marley- his T3ID is 1,2,3,4 and 6.
In table 5 his tasks ID are are 1,2,3,5 and again 5.
So when I look in table T2 his T1 IDs are 1,1,2,4 and 4.
It means that Bob Marley worked on 3 PROJECTS and 2 SUPPORT Tasks.
So when I select Bob Marley result should be:
PROJECT 60
SUPPORT 40
This is the final result from query.
How can I achieve this?
I know that it must be a couple of JOIN statements and of course you can use in WHERE clause
where name='Bob Marley'
If I put
`where name=Tom Cruise
result should be
PROJECT 100`
Thank you
I think this is what you are looking for:
SQL Fiddle Demo
This will give you:
for the sample data you posted.
Note that: This will give you only the
Namethat was involved in projects and tasks. You might need toOUTER JOIN(LEFT or RIGHT)the table instead ofINNER JOINto include thoseNames that were not involved in any tasks or projects (the unmatched rows), withIFNULL()to replacesNULLs with zeros.Update:
You can use the
CONCAT()function to do this, but it will be easier and more readable if you include the previous query inside a subquery and do this in an outer query like so:Updated SQL Fiddle Demo
This will give you:
You can add the
WHEREclause to limit this values to only any user name likeWHERE Name = 'Some name'in the outer query or in the subquery.Update 2
OK, Sorry I missed that. There is no need to
PIVOTorCONCAT()or dynamic SQL to do so. You can do this like so:Updated SQL Fiddle Demo
This will give you: