if / Else / Else if / statement in sql

时间:2014-01-02 07:15:56

标签: php sql if-statement

我有一个类似这样的查询:

SELECT SUM(`table`.points) AS total_points FROM table

这将返回类似这样的内容

|    **points**   |
        324

现在我想在它旁边添加另一个结果,具体取决于用户拥有的总点数并显示它。以下是我想要实现的样本

if (total_points >= 50 && < 100) {
  //display another column next to the points
  another_rows AS total_points + 50  
} else if (total_points >= 100 && < 200) {
  another_rows AS total_points + 100  
} else if (total_points >= 200 && < 300) {
  another_rows AS total_points + 200  
} else if (total_points >= 300 || 300) {
  another_rows AS total_points + 300  
} else {
  another_rows AS total_points
}

欲望结果:

|    **points**   |     **another_row**   |
        324                   824

4 个答案:

答案 0 :(得分:4)

SQL为这些用例准备了一个名为CASE的构造:

SELECT SUM(points) AS total_points,
       SUM(points) +
       CASE 
         WHEN SUM(points) BETWEEN 50 AND 100 THEN 50
         WHEN SUM(points) BETWEEN 100 AND 200 THEN 100
         WHEN SUM(points) BETWEEN 200 AND 300 THEN 200
         WHEN SUM(points) BETWEEN 300 AND 400 THEN 300
         ELSE 500
       END AS another_row
FROM  `table`

答案 1 :(得分:1)

使用CASE WHEN

select SUM(`table`.points) AS total_points,
  CASE SUM(`table`.points) AS total_points 
  WHEN total_points >= 50 AND total_points < 100 THEN
    total_points + 50 AS another_row
  WHEN total_points >= 100 AND total_points < 200 THEN
    total_points + 100 AS AS another_row
  WHEN total_points >= 200 AND total_points < 300 THEN
    total_points + 200 AS AS another_row
  WHEN total_points >= 300 AND total_points < 400 THEN
    total_points + 300 AS AS another_row
  ELSE
    total_points + 500 AS AS another_row
  END CASE
FROM `table`

答案 2 :(得分:0)

Use CASE

SELECT SUM(`table`.points) AS total_points ,Case when (total_points>= 50 &&< 100)
  then
  another_rows AS total_points + 50  
case
 when (total_points >= 100 && total_points< 200) then
   total_points + 100 
case when (total_points >= 200 && total_points< 300)then
   total_points + 200  
case when (total_points >= 300 && total_points< 400)then
  total_points + 300  
else
  total_points + 500 
end as another_rows 

From table

答案 3 :(得分:0)

这是你正在寻找的吗?

SELECT 
    total_points,
    CASE    
        WHEN  
            total_points > 100 
        AND
            total_points < 200
        THEN (total_points + 50)

        WHEN  
            total_points > 200 
        AND
            total_points < 300
        THEN (total_points + 100)
    END AS another_row
FROM
    # from clause
WHERE
    # where clause
相关问题