gpt4 book ai didi

mysql - 在我的 RAILS 应用程序中将 2 个 SELECT 合并为一个 SELECT

转载 作者:行者123 更新时间:2023-11-29 14:37:40 24 4
gpt4 key购买 nike

我有一个名为 ORDEREXECUTIONS 的表,用于存储所有已执行的订单。这是一个多货币应用程序,因此该表有两列 CURRENCY1_ID 和 CURRENCY2_ID。

要获取特定货币对(例如欧元/美元)的所有订单列表,我需要使用行来获取总计:

v = Orderexecution.where("is_master=1 and currency1_id=? and currency2_id=? and created_at>=?",c1,c2,Time.now()-24.hours).sum("quantity").to_d
v+= Orderexecution.where("is_master=1 and currency1_id=? and currency2_id=? and created_at>=?",c2,c1,Time.now()-24.hours).sum("unitprice*quantity").to_d

请注意,我的 SUM() 公式根据货币的顺序而有所不同。例如如果我想要货币对美元的总订购数量,它就会执行(假设美元的货币 ID 为 1,欧元为 2。

v = Orderexecution.where("is_master=1 and currency1_id=? and currency2_id=? and created_at>=?",1,2,Time.now()-24.hours).sum("quantity").to_d
v+= Orderexecution.where("is_master=1 and currency1_id=? and currency2_id=? and created_at>=?",2,1,Time.now()-24.hours).sum("unitprice*quantity").to_d

如何在 RoR 中编写此代码,以便它仅触发一条到 MySQL 的 SQL 语句?

最佳答案

我想这会做:

v = Orderexecution.where("is_master=1 
and ( (currency1_id, currency2_id) = (?,?)
or (currency1_id, currency2_id) = (?,?)
)
and created_at>=?"
,c1, c2, c2, c1, Time.now()-24.hours
)
.sum("CASE WHEN currency1_id=?
THEN quantity
ELSE unitprice*quantity
END"
,c1
)
.to_d

关于mysql - 在我的 RAILS 应用程序中将 2 个 SELECT 合并为一个 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8664151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com