2012-11-30 103 views
0

嗨我有创建SQL的问题。我有表,这样的数据:如何在MYSQL中执行此查询

 
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 

我要为生成数据这样

 
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

where month_b4,e TC ...来自? – RonaldBarzell

+0

他们来自同一张桌子.. – user1867787

+0

这些字段之间的关系是什么? month_b4看起来比这个月少了一个月,我假设year_b4比本月带入上一年的年份少了一年,但qty_b4又如何呢? – RonaldBarzell

回答

0

这个查询将做到这一点创建SQL:

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

+0

谢谢我会试试这个.. – user1867787