我的sql表是这样的:
+----+------------+--------+---------------+---------------+-------------+----------+-------------+---------------------+
| id | msisdn | status | reason | CallRejection | Unavailable | NoAnswer | NetworkBusy | autotimestamp |
+----+------------+--------+---------------+---------------+-------------+----------+-------------+---------------------+
| 1 | 9999999901 | Failed | NoAnswer | 1 | 2 | 2 | 4 | 2013-12-19 15:46:50 |
| 2 | 9999999902 | Failed | NetworkBusy | 4 | 2 | 3 | 2 | 2013-12-19 13:07:42 |
| 3 | 9999999903 | Failed | CallRejection | 6 | 6 | 6 | 5 | 2013-12-19 13:07:53 |
| 4 | 9999999904 | Failed | Unavailable | 2 | 4 | 2 | 0 | 2013-12-19 13:08:03 |
| 5 | 9999999905 | Failed | Misc | 6 | 2 | 6 | 2 | 2013-12-19 13:07:01 |
| 6 | 9999999906 | Failed | NoAnswer | 1 | 3 | 1 | 6 | 2013-12-19 13:07:24 |
| 7 | 9999999907 | Failed | NetworkBusy | 6 | 6 | 2 | 3 | 2013-12-19 13:07:42 |
| 8 | 9999999908 | Failed | CallRejection | 8 | 3 | 3 | 0 | 2013-12-19 13:07:53 |
| 9 | 9999999909 | Failed | Unavailable | 3 | 8 | 5 | 6 | 2013-12-19 13:08:03 |
| 10 | 9999999910 | Failed | Misc | 8 | 4 | 0 | 4 | 2013-12-19 13:07:01 |
+----+------------+--------+---------------+---------------+-------------+----------+-------------+---------------------+
我想根据每行reason
列的值提取每个原因的值。例如:
row 1
应该提供2
因为reason
列有noanswer
,因此应该返回该特定列的值,即noanswer
。
实际上,在将返回的值与常量进行比较后,我必须选择多行。我可以通过以下方法完成此操作:
select @col := reason from msisdn_table where id=1;
SET @a = concat('select ', @col, ' from msisdn_table where id=1');
PREPARE STMT FROM @a;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
但这不是一个非常有前途的解决方案,因为它只用于一行,我将不得不使用for循环以获得1000行的块,这不会非常有效。什么是更有效的方式?
答案 0 :(得分:3)
试试这个:
SELECT id,
reason
CASE
WHEN reason = 'NoAnswer' THEN NoAnswer
WHEN reason = 'NetworkBusy' THEN NetworkBusy
END AS value
FROM table1
它应该给你一个这样的输出:
+----+------------+----------+
| id | reason | value |
+----+------------+----------+
| 1 | NoAnswer | 2 |
+----+------------+----------+