如何使用MySQL在同一行显示以前的数据?

时间:2012-08-13 06:08:26

标签: mysql sql ruby-on-rails ruby ruby-on-rails-3.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")

1 个答案:

答案 0 :(得分: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;