在布尔列上使用CASE WHEN

时间:2015-10-26 19:19:16

标签: postgresql

这是Postgres 8.x. Speicifcally Redshift。

表格在所有3列中都为FALSE。但是,当我运行此查询时,它将返回,就好像所有都是TRUE

SELECT
count(CASE WHEN facebook THEN 1 ELSE 0 END)
, count(CASE WHEN instagram THEN 1 ELSE 0 END)
, count(CASE WHEN twitter THEN 1 ELSE 0 END)
FROM public.sampletable

不确定我做错了什么。我还试过CASE WHEN facebook = TRUE

我确保单元格不是NULL或其他任何东西

2 个答案:

答案 0 :(得分:2)

问题是COUNT计数10相同。一种方法是将要避免的值更改为NULL

SELECT
  count(CASE WHEN facebook  THEN 1 ELSE NULL END)
, count(CASE WHEN instagram THEN 1 ELSE NULL END)
, count(CASE WHEN twitter   THEN 1 ELSE NULL END)
FROM public.sampletable

SELECT
   count(CASE WHEN facebook  THEN 1 END) -- ELSE NULL is default so you can skip
  ,count(CASE WHEN instagram THEN 1 END)
  ,count(CASE WHEN twitter   THEN 1 END)
FROM public.sampletable

或评论中提出的Marc B使用SUM

SELECT
 SUM(CASE WHEN facebook THEN 1 ELSE 0 END)
,SUM(CASE WHEN instagram THEN 1 ELSE 0 END)
,SUM(CASE WHEN twitter THEN 1 ELSE 0 END)
FROM public.sampletable

修改

如果您需要合计金额,您可以使用:

SUM(CASE WHEN facebook THEN 1 ELSE 0 END +
    CASE WHEN twitter THEN 1 ELSE 0 END +
    CASE WHEN instagram THEN 1 ELSE 0 END)

编辑2

这个答案的灵感来自answer below。您可以简单地投射数据:

SELECT SUM(CAST(facebook AS INT)),
       SUM(CAST(instagram AS INT)),
       SUM(CAST(twitter AS INT)),
       SUM(CAST(facebook AS INT) + CAST(instagram AS INT) + CAST(twitter AS INT))
FROM sampletable;

SqlFiddleDemo

答案 1 :(得分:2)

您可以使用简单强制转换为整数:

select
    sum(facebook::int) facebook,
    sum(instagram::int) instagram,
    sum(twitter::int) twitter,
    sum(facebook::int+ instagram::int+ twitter::int) total
from public.sampletable;