2012-11-30 152 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