在sql中添加两列的值

时间:2014-01-02 09:05:50

标签: php mysql sql if-statement case

我的代码类似于下面的代码

SELECT SUM(points_1) AS total_points_1, SUM(points_2) AS total_points_2,

       total_points_1 +
       CASE 
         WHEN total_points_1 BETWEEN 50 AND 100 THEN 50
         WHEN total_points_1 BETWEEN 100 AND 200 THEN 100
         WHEN total_points_1 BETWEEN 200 AND 300 THEN 200
         WHEN total_points_1 BETWEEN 300 AND 400 THEN 300
         ELSE 500
       END AS another_row_1,

       total_points_2 +
       CASE 
         WHEN total_points_2 BETWEEN 50 AND 100 THEN 50
         WHEN total_points_2 BETWEEN 100 AND 200 THEN 100
         WHEN total_points_2 BETWEEN 200 AND 300 THEN 200
         WHEN total_points_2 BETWEEN 300 AND 400 THEN 300
         ELSE 500
       END AS another_row_2,

FROM  `table`

我的目标是添加another_row_1another_row_2

的结果

我已尝试在END AS another_row_2,之后立即执行以下行但无效

SUM(another_row_1 + another_row_2)AS total_sum

2 个答案:

答案 0 :(得分:2)

首先要减少混乱并提高可维护性我建议将点重新计算逻辑(用CASE实现的逻辑)包装到函数中

CREATE FUNCTION add_points(_points INT)
RETURNS INT
RETURN 
  _points + 
  CASE 
    WHEN _points BETWEEN  50 AND  99 THEN 50
    WHEN _points BETWEEN 100 AND 199 THEN 100
    WHEN _points BETWEEN 200 AND 299 THEN 200
    WHEN _points BETWEEN 300 AND 399 THEN 300
    ELSE 500
  END;

注意:您可能需要将数据类型从INT更改为DECIMAL(n,m)(根据您的实际数据类型points_1和{{1 }})

现在查询看起来像

points_2

示例输出:

| TOTAL_POINTS_1 | TOTAL_POINTS_2 | ANOTHER_TOTAL_1 | ANOTHER_TOTAL_2 | TOTAL_SUM |
|----------------|----------------|-----------------|-----------------|-----------|
|            165 |            386 |             265 |             686 |       951 |

这是 SQLFiddle 演示

答案 1 :(得分:1)

您必须将其置于内部查询

SELECT (res.another_row_1 + res.another_row_2) AS total_sum FROM
(
SELECT SUM(points_1) AS total_points_1, SUM(points_2) AS total_points_2,

       total_points_1 +
       CASE 
         WHEN total_points_1 BETWEEN 50 AND 100 THEN 50
         WHEN total_points_1 BETWEEN 100 AND 200 THEN 100
         WHEN total_points_1 BETWEEN 200 AND 300 THEN 200
         WHEN total_points_1 BETWEEN 300 AND 400 THEN 300
         ELSE 500
       END AS another_row_1,

       total_points_2 +
       CASE 
         WHEN total_points_2 BETWEEN 50 AND 100 THEN 50
         WHEN total_points_2 BETWEEN 100 AND 200 THEN 100
         WHEN total_points_2 BETWEEN 200 AND 300 THEN 200
         WHEN total_points_2 BETWEEN 300 AND 400 THEN 300
         ELSE 500
       END AS another_row_2,

FROM  `table`
) AS res