开发者

MySQL: SELECT an extra column categorizing another column based on IF statements

Suppose this command: SELECT sessionID, SessionLength FROM mytable;

Generates this table:

+-----------+---------------+
| sessionID | SessionLength |
+-----------+---------------+
|         1 | 00:20:31      | 
|         2 | 00:19:54      | 
|         3 | 00:04:01      | 

  ...
|      7979 | 00:00:15      | 
|      7980 | 00:00:00      | 
|      7981 | 00:00:00      | 
+-----------+---------------+
7981 rows in set (0.92 sec)

But I want to generate a table like this:

+-------开发者_JAVA技巧----+---------------+--------+
| sessionID | SessionLength | Size   |
+-----------+---------------+--------+
|         1 | 00:20:31      | BIG    |
|         2 | 00:19:54      | BIG    |
|         3 | 00:04:01      | MEDIUM |

  ...
|      7979 | 00:00:15      | SMALL  |
|      7980 | 00:00:00      | SMALL  |
|      7981 | 00:00:00      | SMALL  |
+-----------+---------------+--------+
7981 rows in set (0.92 sec)
  • Something is big when it's SessionLength > 10
  • Something is medium when it's SessionLength <= 10 AND SessionLength >=1
  • Something is small whne it's SessionLength > 1

Conceptually what I want to do is this:

SELECT 
   sessionID, 
   SessionLength,
   (SessionLength > 10 ? "BIG" : (SessionLength < 1 : "SMALL" : "MEDIUM"))
FROM mytable;

Is there an easy way to do this?


Yes,

SELECT
   sessionID, SessionLength,
   CASE WHEN SessionLength > 10 THEN 'BIG'
        WHEN SessionLength < 1 THEN 'SMALL'
        ELSE 'MEDIUM'
   END 
FROM mytable;


SELECT
    sessionID,
    SessionLength,
    IF( SessionLength > 10, "BIG",
        IF( SessionLength < 1, "SMALL", "MEDIUM")) AS Size
FROM mytable;

HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜