我有一个名为temp_rfm的表,其中col1实际上是客户ID(我有一个非法混合的联盟问题)和calc_date,它正在增加几个月的开始。
SELECT * FROM temp_rfm ;
col1 | calc_date
-----|-----------
20 | 2016-02-01
20 | 2016_03_01
20 | 2016-04-01
21 | 2016-01-01
21 | 2016-02-01
21 | 2016_03_01
21 | 2016-04-01
21 | 2016-05-01
42 | 2017_06_01
42 | 2017-07-01
42 | 2017-08-01
我想要的是在temp_rfm表中输入一列来增加每个客户的每个日期,如下所示:
col1 | calc_date | row_number
-----|-----------|-----------
20 | 2016-02-01| 1
20 | 2016_03_01| 2
20 | 2016-04-01| 3
21 | 2016-01-01| 1
21 | 2016-02-01| 2
21 | 2016_03_01| 3
21 | 2016-04-01| 4
21 | 2016-05-01| 5
42 | 2017_06_01| 1
42 | 2017-07-01| 2
42 | 2017-08-01| 3
我使用用户定义的变量通过简单的select语句成功完成了这项工作。但是如果我想把它永久地放在一个表中(更新表或插入或设置),它就不起作用了。
以下是我尝试的查询及其结果:
UPDATE temp_rfm t inner join
(SELECT customer_id, customer_id COLLATE utf8_unicode_ci as col2
from temp_rfm) T
USING (customer_id) set t.col2=T.col2;
set @col2 = 1, @num :=1;
Update temp_rfm t inner join
(select col2,
@num := if (@col2 = col2, @num + 1, 1) as row_number,
@col2 := col2 as dummy
from temp_rfm
order by col2, calc_date ) T
USING (col2) set t.row_number = T.row_number and t.dummy = T.dummy ;
然后当我进行查询时 SELECT col1,calc_date,row_number,dummy 来自temp_rfm;
col1 | calc_date | row_number| dummy
-----|-----------|-----------|------
20 | 2016-02-01| 1 | 20
20 | 2016_03_01| 1 | 20
20 | 2016-04-01| 1 | 20
21 | 2016-01-01| 1 | 21
21 | 2016-02-01| 1 | 21
21 | 2016_03_01| 1 | 21
21 | 2016-04-01| 1 | 21
21 | 2016-05-01| 1 | 21
42 | 2017_06_01| 1 | 42
42 | 2017-07-01| 1 | 42
42 | 2017-08-01| 1 | 42
我也尝试了以下查询,得到了类似的结果!
set @customer_id_chg = 1 , @num=1;
INSERT INTO temp_rfm (row_number, dummy)
(select
@num := if ((@col2 =col2), @num + 1, 1) as row_number,
@col2 := col2 as dummy
from temp_rfm
order by col2, calc_date);
set @customer_id_chg = 1 , @num=1;
select customer_id_chg, transaction_date, value_realised, items_ordered, date_diff,
@num := if (@customer_id_chg = customer_id_chg, @num + 1, 1) as row_number,
@customer_id_chg:= customer_id_chg as dummy
from transactions
where customer_id = 10073
order by customer_id_chg, transaction_date;
任何帮助将不胜感激!我正在研究MySQL工作台。
答案 0 :(得分:0)
未经测试的代码:
update temp_rfm t
set t.dummy = (select ifnull(max(dummy), 0) + 1 from temp_rfm);
在提出这个问题时,请告诉我是否错了。原因是每当我们想要设置一个新的虚拟对象时,我们会找到先前已知的最大值(默认为0)并向其添加1。