-1

This is my first table t1:

-----------------------------
| code | month      | value |
-----------------------------
| 101  |august      | 1     |
| 101  |September   | 3     |
| 101  |November    | 7     |
| 202  |august      | 5     |
| 202  |September   | 6     |
| 202  |November    | 9     |
| 303  |august      | 9     |
| 303  |September   | 3     |
-----------------------------

I want to create the second table t2 (view table) looks like

------------------------------------------
| code | month      | value | value_begin |
------------------------------------------
| 101  |august      | 1     |0            |
| 101  |September   | 3     |1            |
| 101  |November    | 7     |4 (3+1)      |
| 202  |august      | 5     |0            |
| 202  |September   | 6     |5            |
| 202  |November    | 2     |11 (6+5)     |
| 303  |august      | 9     |0            |
| 303  |september   | 3     |9            |
-------------------------------------------

value_begin is sum value and value_begin above the row, like in row 101-November value_begin is 4 from value 3 (above) and value_begin 1 (above).

Is this possible to create the second table t2 in view?

4

1 回答 1

0

这是 SQLFIddel 演示

以下是 Demo 中显示的视图:

Create View V1 as
select T1.code,T1.Month,T1.Value,
       sum(IFNULL(T2.value,0)) as value_begin
  from Table1 T1
 left join Table1 T2
    On T1.code = T2.code 
   and month(str_to_date(substring(T1.month,1,3),'%b')) > month(str_to_date(substring(T2.month,1,3),'%b'))
Group by T1.code,T1.Month,T1.Value 
Order by t1.code,month(str_to_date(substring(T1.month,1,3),'%b'))
;

不允许添加变量,因此我以前的方法没有帮助。而且您需要考虑变量,这也是不可能的。在这里,我使用了您的表格的逻辑来克服这种情况。希望这可以帮助。如果有任何疑问,请回复。


注意:我在演示中添加了几行来检查计算验证。

于 2013-10-03T07:01:33.773 回答