SQLite的。如果出现特定值,如何在不同列中返回1和0

时间:2011-10-27 21:21:28

标签: sql sqlite

您好我是SQL新手,尤其是SQLite,与我刚刚学到的相比,它与sql相比已被删除。

我有一张看起来像这样的表:

id_foo | foo_val
________________
  1    |    3
  1    |    1
  2    |    2

如果出现特定值,我需要一个能给我一个值为1和0的表的查询:

id_foo | val1 | val2 | val3 | val4 |
_______|______|______|______|______|
  1    |   1  |   0  |  1   |  0   |
  2    |   0  |   1  |  0   |  0   |

我尝试使用“if exists”命令执行此操作,但“sqliteman”无法识别此命令:/

2 个答案:

答案 0 :(得分:1)

应该这样做:

SELECT id_foo
      ,max(CASE WHEN foo_val = 1 THEN 1 ELSE 0 END) AS val1
      ,max(CASE WHEN foo_val = 2 THEN 1 ELSE 0 END) AS val2
      ,max(CASE WHEN foo_val = 3 THEN 1 ELSE 0 END) AS val3
      ,max(CASE WHEN foo_val = 4 THEN 1 ELSE 0 END) AS val4
FROM   tbl
GROUP  BY id_foo
ORDER  BY id_foo

答案 1 :(得分:0)

SQLite uses 1 and 0 for booleans所以如果你不喜欢Erwin的CASE,你可以这样做:

select id_foo,
       max(foo_val = 1) as val1,
       max(foo_val = 2) as val2,
       max(foo_val = 3) as val3,
       max(foo_val = 4) as val4
from pancakes
group by id_foo
order by id_foo

但请记住,使用CASE应该可以在任何地方使用。