2010-11-15 13 views
0

Supposons que cette commande: SELECT sessionID, SessionLength FROM mytable;MySQL: SELECT une colonne supplémentaire catégoriser une autre colonne basée sur les instructions IF

Génère ce tableau:

+-----------+---------------+ 
| 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) 

Mais je veux générer une table comme ceci:

+-----------+---------------+--------+ 
| 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) 
  • Quelque chose est big lorsqu'il est SessionLength > 10
  • Quelque chose est medium quand il est SessionLength <= 10 AND SessionLength >=1
  • Quelque chose est small whne il est SessionLength > 1

Conceptuellement ce que je veux faire est la suivante:

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

est-il un moyen facile de le faire?

Répondre

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

HTH

2

Oui,

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