【问题标题】:How to use "case-when" in Ecto Queries in elixir?如何在 Elixir 的 Ecto 查询中使用“case-when”?
【发布时间】:2015-12-01 13:46:51
【问题描述】:

我有一个 SQL 查询,例如:
SELECT SUM(CASE WHEN <table_name>.status = '2' THEN 1 ELSE 0 END) FROM <table name>

我想为上面写相应的 Ecto Query。比如:

from t in <table_name>, select: sum(...)

与上述案例中的“case-when”有何类比?

【问题讨论】:

标签: sql postgresql elixir phoenix-framework ecto


【解决方案1】:

如评论所说,可以使用fragment/1

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

如果你想指定表,这对我有用:

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

【讨论】:

  • 这可行,但只是一个小问题...如何将表名与片段中的“table_name”.status 等状态相关联?
【解决方案2】:

您还可以利用宏来扩展 Ecto 查询语言:

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

然后像这样使用它:

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

【讨论】:

    猜你喜欢
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多