如何使用选择大小写和别名对输出求和

时间:2019-05-09 11:32:30

标签: sql select

我正在尝试使用选择案例和别名字段来创建总里程数。

我在下面有当前有效的查询,并将输出total_miles数字。

SELECT ROUND(SUM(s.activity_steps * d.dist_activity_duration / 2000), 2) AS total_miles 
FROM distance d
JOIN activities a 
ON a.id = d.dist_activity_id
JOIN steps s
ON s.id = a.steps_id
JOIN members AS m   
ON d.member_id = m.id
AND m.id = ?

我必须在数据库结构中引入新列(dist_is_duration-int),以指示dist_activity_duration值是否需要转换为英里或已输入为英里。

dist_activity_duration       dist_is_duration
50                           1
900                          1
60                           0
450                          1

我已经更新了原始查询,以使用案例来检查持续时间是否需要转换。

SELECT CASE 
WHEN d.dist_is_duration = 1 THEN
ROUND(SUM(s.activity_steps * d.dist_activity_duration / 2000), 2)
WHEN d.dist_is_duration = 0 THEN
ROUND(SUM(d.dist_activity_duration), 2)
END AS total_miles
FROM distance d
JOIN activities a 
ON a.id = d.dist_activity_id
JOIN steps s
ON s.id = a.steps_id
JOIN members AS m   
ON d.member_id = m.id
AND m.id = 1
GROUP BY d.dist_is_duration

这将输出两个值

total_miles
25.00
2154.37

我的目标是获得total_miles作为总数。

2 个答案:

答案 0 :(得分:2)

这样对您有用吗?

sum(iif(d.dist_is_duration = 1, (s.activity_steps * d.dist_activity_duration) / 2000,d.dist_activity_duration)

如果您只想使用一个号码,也需要摆脱分组。

答案 1 :(得分:2)

如果您的数据库不支持iif(由@ Van-Macintosh提议):

getArtists(query) {
   let params = {
        q: query,
        type: 'track,artist',
        market: 'US',
        limit: 14,
        offset: 5
    };

    if (typeof query !== 'string') {
        delete params.q;
    }

    console.log(params) 

    return this.$http.get("https://api.spotify.com/v1/search", { 
params }).then(function mySuccess(response) {
        console.log(response.data);
    }, function myError(response) {
        console.log(response);
    });
  };