1

我在显示数据库中的数据时遇到问题。我有jos_stock带字段的表rem_balancerem_balance有价值0, 126, 12, 9。在我的网站上。rem_balance显示它取决于周,即 2012 年第 26 周,余额的值为 0。这意味着 2012 年第 25 周 = 126、2012 年第 24 周 = 12 和 2012 年第 23 周 = 9。

我要做的就是如果当前周的值是 26 等于 0。它将显示之前的余额 126。我该怎么做?有什么建议吗?我正在使用 Ruby on Rails。

这是我在模型中的查询:

SELECT("jos_product.id, jos_product.product_code AS code, jos_product.name, 
pc.id AS category_id, pc.name AS category_name, thumbnail, location, 
original_image,CONCAT(sm.year, '/', sm.week) as week_start, 
CONCAT(sm2.year, '/', sm2.week) AS reprint_week, pr.quantity AS reprint_qty,
jos_stock.rem_balance AS balance")
.joins("INNER JOIN jos_product_category AS pc ON pc.id = jos_product.product_category")
.joins("INNER JOIN jos_stock_movement AS sm ON sm.id = jos_product.start_week")
.joins("LEFT OUTER JOIN jos_stock ON jos_stock.product_id = jos_product.id")
.joins("LEFT OUTER JOIN (select product, max(stock_movement) AS reprint, quantity from 
jos_product_reprint group by product) AS pr ON pr.product IN (jos_product.id)")
.joins("LEFT OUTER JOIN jos_stock_movement AS sm2 ON sm2.id = pr.reprint")
.where("jos_product.published = 1 #{ search_query }")
.order("jos_product.product_code ASC")
.group("jos_product.product_code")
4

1 回答 1

2

虽然我无法向您展示可以解决您的问题的确切查询(我没有您所有表的 DDL),但我可以向您展示如何检索前一行数据的假设示例。这里使用的是您的问题中描述的测试数据(我假设您在哪里写“即 2012 年第 36 周,剩余余额的值为 0”,您的意思是“即 2012 年第26周,剩余余额的值是0”。

希望您可以从中学习,并将其用于您的 Ruby on Rails 查询:

drop table if exists test_jos_stock;

create table test_jos_stock
(
id int unsigned not null primary key auto_increment,
rem_balance int not null default 0,
year int not null default 0,
week int not null default 0
);

insert into test_jos_stock (rem_balance,year,week) values (9,2012,23);
insert into test_jos_stock (rem_balance,year,week) values (12,2012,24);
insert into test_jos_stock (rem_balance,year,week) values (126,2012,25);
insert into test_jos_stock (rem_balance,year,week) values (0,2012,26);

select js.year,js.week,js.rem_balance,
case when js.rem_balance = 0 then @prev_rem_balance else js.rem_balance end as rem_balance_zero_or_prev,
@prev_rem_balance := js.rem_balance
from test_jos_stock js
inner join (SELECT @prev_rem_balance := 0) as t
order by year,week;
于 2012-08-13T08:53:12.403 回答