I have two tables in my database, One is category and second is an entry table.
My Category Table is like below:
----------------------------------
| Cat_ID | cat_type | cat_value |
----------------------------------
| 201 | running | 1 |
| 202 | cycling | 4 |
----------------------------------
My Entry Table is like below:
-------------------------------
| user_id | cat_ID | distance |
-------------------------------
| 1 | 201 | 50 |
| 1 | 201 | 50 |
| 1 | 202 | 100 |
| 1 | 202 | 100 |
| 2 | 201 | 10 |
| 2 | 201 | 10 |
-------------------------------
So Now I want to total distance for user ID "1" but here one condition is that for 201 categories the sum of the total will divide by one and for 202 category total distance will divide by 4 as per category table in cat_value.
Means i want total distance like ((50+50)/1 + (100+100)/4)
So, how can i do this?
Use join and sub-query
select
sum(t1.totald/c.cat_value) as total_distance
from
cat c
join
(select
sum(distance) totald, user_id, cat_id
from
entry where user_id=1 --- if you just want for userid=1
group by
user_id, cat_id) t1 on c.Cat_ID = t1.Cat_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.