10

这是我的表格数据:

id | days
-----------
1  | 10
2  | 20
3  | 30
4  | 25
5  | 5

我想要这样的结果:

id  days    resultcolumn
1    10     less than 10
2    20     less than 20
3    30     less than 30
4    25     less than 30
5    5      less than 10

我使用了以下查询:

SELECT id,days,
  CASE days 
    WHEN days<=10 THEN 'less than 10'
    WHEN days<=20 THEN 'less than 20'
    WHEN days<=30 THEN 'less than 30'
  END AS 'days2'
FROM calender

但我得到了这样的结果数据:

id  days    resultcolumn
1    10       {null}
2    20       {null}
3    30       {null}
4    25       {null}
5    5        {null}

如何使用CASEMySQL 中的语句获得原始结果?

4

4 回答 4

11

试试这个:

SELECT
      id,
      days,
      CASE WHEN days<=10 THEN 'less than 10'
           WHEN days<=20 THEN 'less than 20'
           WHEN days<=30 THEN 'less than 30' END AS 'days2'
    FROM calender
于 2013-01-01T15:11:03.127 回答
3

您只需要在 CASE 之后删除几天:

SELECT
  id,
  days,
  CASE WHEN days<=10 THEN 'less than 10'
       WHEN days<=20 THEN 'less than 20'
       WHEN days<=30 THEN 'less than 30' END AS 'days2'
FROM calender
于 2013-01-01T14:19:49.450 回答
3

你可以在没有CASE ... WHEN构造的情况下做到这一点。只需使用简单的数学。

SELECT *, 
    CONCAT('less than ', CEIL(`days`/10)*10) AS `resultcolumn` 
FROM `Table1`

sqlfiddle

这可以防止分支预测失败。因此对于大型数据集会更快

于 2013-01-01T14:35:43.710 回答
1

试试这个:

SELECT id,days,
  CASE  
      WHEN days<=10 THEN 'less than 10'
      WHEN days<=20 THEN 'less than 20'
      WHEN days<=30 THEN 'less than 30'
  END AS 'resultcolumn'
FROM calender
于 2013-01-01T16:46:07.863 回答