如何使用“case-when"在灵丹妙药的 Ecto 查询中? [英] How to use "case-when" in Ecto Queries in elixir?

查看:62
本文介绍了如何使用“case-when"在灵丹妙药的 Ecto 查询中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

.

I have an SQL query like :
SELECT SUM(CASE WHEN <table_name>.status = '2' THEN 1 ELSE 0 END) FROM <table name>.

我想为上面写相应的Ecto Query.类似于:

I want to write the corresponding Ecto Query for the above. Something like:

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

上述案例中case-when"的类比是什么?

What is the analogy to "case-when" in the above case?

推荐答案

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

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)

这篇关于如何使用“case-when"在灵丹妙药的 Ecto 查询中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆