我试图插入要从中提取的表中不存在的行,它按days_to_cancel列排序,并从零开始,并有新的Year / Month项。我正在使用以下查询:
CREATE TABLE reporting.tbl_exec_retention_curve_cumulative (days_to_cancel int, cancels int, cumulative_cancels int, enroll_dt varchar(50));
SELECT rc.days_to_cancel,
rc.cancels,
(@run_total := CASE WHEN rc.days_to_cancel <> 0 THEN @run_total +
rc.cancels ELSE rc.cancels END) AS cumulative_cancels,
LEFT(rc.client_enroll_dt,7) AS client_enroll_dt
FROM (SELECT rc.days_to_cancel,
SUM(CASE WHEN rc.client_status = 'CAN' THEN 1 ELSE 0 END) AS cancels,
LEFT(rc.client_enroll_dt,7) AS client_enroll_dt
FROM t1.table rc
GROUP BY 1,3
ORDER BY 3,1
) rc
JOIN (SELECT @run_total := 0) r
GROUP BY 1,4
ORDER BY 4,1;
我得到以下样本结果
days_to_cancel | cancels | cumulative_cancels | client_enroll_dt
---------------+---------+--------------------+------------------
42 | 2 | 376 | 2019-02
47 | 0 | 376 | 2019-02
0 | 0 | 0 | 2019-03
10 | 4 | 4 | 2019-03
11 | 9 | 13 | 2019-03
所以我的目标是输入缺少的日期,并在输入那些缺少的日子的新行时,使用以前的cumulative_cancels和enroll_dt值,将0用作取消列。我已经尝试了多种方法,包括使用变量,但我一无所获。我不知道是否有可能首先考虑到行不存在。如果有问题,我使用的是MariaDB 10.0.35版。
答案 0 :(得分:0)
我只是想像您从t1.table
获取了数据,并希望将结果插入同一张表中。
我的解决方案是将结果放入临时表中,然后通过左联接查找丢失的日子。
SELECT rc.days_to_cancel,
rc.cancels,
(@run_total := CASE WHEN rc.days_to_cancel <> 0 THEN @run_total +
rc.cancels ELSE rc.cancels END) AS cumulative_cancels,
LEFT(rc.client_enroll_dt,7) AS client_enroll_dt
--put your result into a temp table
into #temp
FROM (SELECT rc.days_to_cancel,
SUM(CASE WHEN rc.client_status = 'CAN' THEN 1 ELSE 0 END) AS cancels,
LEFT(rc.client_enroll_dt,7) AS client_enroll_dt
FROM t1.table rc
GROUP BY 1,3
ORDER BY 3,1
) rc
JOIN (SELECT @run_total := 0) r
GROUP BY 1,4
ORDER BY 4,1;
insert into t1.table (days_to_cancel, cancels,cumulative_cancels, client_enroll_dt)
select tm.days_to_cancel, tm.cancels, tm.cumulative_cancels, tm.client_enroll_d from #temp tm
left join t1.table rc on rc.days_to_cancel = tm.days_to_cancel
where rc.days_to_cancel is null --find out missing days
drop table #temp