我的表结构是
customer column1 column2(int)
1 sale 2
1 return 1
1 sale 3
1 sale 1
1 return 1
问题: -
创建一个具有起始值`column3 = 0`的虚拟列(column3),并根据`column1`和`column2`值更新其值。我找不到一起创建和更新虚拟列的查询。
e.g。 IF(column1='sale',column3 + column2, column3-column2 )
// start value of column3 = 0 for each product
customer column1 column2(int) column3
1 sale 2 2 //0+2 because it is a sale
1 return 1 1 //2-1 because it is a return
1 sale 3 4 //1+3 because it is a sale
1 sale 1 6 //4+2 because it is a sale
1 return 1 4 //6-2 because it is a return
答案 0 :(得分:1)
CROSS JOIN应该解决这个问题:
SELECT
t.column1,
t.column2,
CASE
WHEN t.column1 = 'sale' THEN
@id :=@id + t.column2
ELSE
@id :=@id - t.column2
END AS column3
FROM
(SELECT @id:=0) var
CROSS JOIN table1 t