How to use "case-when" in Ecto Queries in elixir?

Like the comment said, you can use fragment/1:

query = from t in <Model>, select: fragment("SUM(CASE WHEN status = ? THEN 1 ELSE 0 END)", 2)

If you want to specify the table, this works for me:

query = from t in <Model>, select: fragment("SUM(CASE WHEN ? = ? THEN 1 ELSE 0 END)", t.status, 2)

You can also leverage on macros to extend Ecto query language:

defmacro case_when(condition, do: then_expr, else: else_expr) do
  quote do
    fragment(
      "CASE WHEN ? THEN ? ELSE ? END",
      unquote(condition),
      unquote(then_expr),
      unquote(else_expr)
    )
  end
end

Then use it like this:

query = from t in <Model>,
  select: case_when t.status == 2
    do 1
    else 0
  end