您好我有创建SQL的问题。我有表格和这样的数据:
id month year id_type qty 1 10 2012 1 5 2 10 2012 2 4 3 10 2012 3 3 4 10 2012 4 5 5 11 2012 1 1 6 11 2012 2 2 7 12 2012 1 3 8 12 2012 2 2
我想创建SQL来生成像这样的数据
id_type month year qty month_b4 year_b4 qty_b4 1 10 2012 5 9 2012 0 2 10 2012 4 9 2012 0 3 10 2012 3 9 2012 0 4 10 2012 5 9 2012 0 1 11 2012 1 10 2012 5 2 11 2012 2 10 2012 4 1 12 2012 1 11 2012 1 2 12 2012 2 11 2012 2
答案 0 :(得分:0)
此查询将执行此操作:
select
sales.id_type as id_type,
sales.month as month,
sales.year as year,
sales.qty as qty,
prev.month as month_b4,
prev.year as year_b4,
prev.qty as qty_b4
from
sales,
sales as prev
where
sales.id_type = prev.id_type and
((sales.month=1 and prev.month=12 and prev.year=sales.year-1) or
prev.month = sales.month - 1);
我也可以在小提琴上练习它: http://sqlfiddle.com/#!2/ed3af/14