我在mysql中有一个列,想将列更改为[0 1 0 1]类型进行数据处理,
例如,
+------+
| area |
+------+
| 1 |
| 2 |
+------+
我想将上面的表格改为以下表格:
+--------+--------+
| apple | banana |
+--------+--------+
| 1 | 0 |
| 0 | 1 |
+--------+--------+
简而言之 如果area =' 1',则apple = 1 如果area =' 2',则banana = 1
在参考某些网站后我的代码如下,但它没有工作..
insert into test1 (apple, banana)
-> select count(case when area = '1' then 1 else 0 end) as apple,
-> select count(case when area = '2' then 1 else 0 end) as banana
-> from test3;
错误说"您的SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便使用接近'选择计数(区域=' 2'然后1其他0结束时)的正确语法作为香蕉 来自test3'在第3行", 但我找不到任何理由.. 请有人帮助我..?
谢谢..> _<
答案 0 :(得分:1)
如果您为每个ID都预定义了关键字(例如1表示苹果,2表示香蕉),那么您可以这样做...
select SUM(case when area = '1' then 1 else 0 end) as apple,0 as banana from test3
union select 0 ,SUM(case when area = '2' then 1 else 0 end) from test3;
答案 1 :(得分:1)
SELECT
CASE WHEN area = 1 THEN 1 ELSE 0 END as apple,
CASE WHEN area = 2 THEN 1 ELSE 0 END as banana
FROM T