我有一个查询以我想要的方式工作,通过直接执行SQL,但我很好奇(仅仅是出于我自己的学习目的),如果可以在ActiveRecord语句中完成同样的事情吗?
我最挣扎的部分是此查询的COALESCE部分,它只是确保来自LEFT JOIN的任何NULL值都被计为零,以保持求和顺序。
有什么想法吗?我使用的是Postgres。
.container {
height: 100px;
overflow: hidden;
}
.left {
float: left;
background: #00FF00;
width: 25%;
overflow: hidden;
height: 100%;
}
.right {
display: inline-block;
width: 50%;
background: #0000ff;
height: 100%;
}
.bottom {
float: right;
background: #ff0000;
display: inline-block;
width: 25%;
height: 100%;
}
@media only screen and (max-width: 900px) {
.container {
height: auto;
overflow: hidden;
}
.left {
float: left;
background: #00ff00;
width: 25%;
overflow: hidden;
height: 100px;
}
.right {
float: none;
width: 75%;
background: #0000ff;
height: 100px;
}
.bottom {
position: relative;
float: none;
background: #ff0000;
width: auto;
overflow: hidden;
height: 50px;
display: inherit;
}
}
这是我与AR等同的最接近的。当我尝试添加一个总和或类似的东西时,那就是当它出错时。
SELECT Inventories.id, Inventories.name, Inventories.unit_of_measure,
COALESCE(Sum(Stocks.count),0) as totalcount
FROM Inventories
LEFT JOIN Stocks
ON Inventories.id = Stocks.inventory_id
WHERE Inventories.property = 'material' AND Inventories.organization_id = #{current_organization.id}
GROUP BY Inventories.id, Stocks.inventory_id
ORDER BY totalcount ASC
LIMIT(5)")
答案 0 :(得分:0)
您可以使用ActiveRecord::QueryMethods#select
:
your_relation.select("column1, column2, COALESCE(1,2) AS column3").left_joins...