繁体   English   中英

需要查询以查找某些情况下的总距离吗?

[英]Need a query to find total distance with some condition?

我的数据库中有两个表,一个是类别,第二个是条目表。

我的类别表如下:

----------------------------------
| Cat_ID |  cat_type | cat_value |
----------------------------------
|  201   |  running  |     1     |
|  202   |  cycling  |     4     |
----------------------------------

我的条目表如下:

-------------------------------
| user_id | cat_ID | distance |
-------------------------------
|    1    |   201  |    50    |
|    1    |   201  |    50    |
|    1    |   202  |   100    |
|    1    |   202  |   100    |
|    2    |   201  |    10    |
|    2    |   201  |    10    |
-------------------------------

因此,现在我要为用户ID“ 1”求出总距离,但是这里的一个条件是,根据cat_value中的分类表,对于201个类别,总和将除以1,对于202个类别,总距离将除以4。

表示我想要的总距离像((50 + 50)/ 1 +(100 + 100)/ 4)

那么,我该怎么做呢?

使用联接和子查询

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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