不确定如何描述我想从这个问题中得到什么,但是这里......
我有一个客户购买表't1',其中包含有关购买的信息:客户ID,日期,客户独处时的布尔值以及购买金额。在第二个表中,t2
是另一个相同客户ID的列表,其中包含日期和布尔值,表示它们是否是独立的。
我想更新第二个表格,其中包含之前x次购买的价值的平均值,以及他们是否单独购买。
我用以下方式设置表格:
DROP TABLE IF EXISTS t1;
DROP TABLE IF EXISTS t2;
CREATE TABLE t1 (cid INT, d DATE, i INT, v FLOAT);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-01', 0, 10);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-02', 1, 20);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-03', 1, 30);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-04', 1, 40);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-05', 0, 50);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-06', 0, 60);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-07', 0, 70);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-08', 1, 80);
INSERT INTO t1 (cid, d,i,v) VALUES (1,'2001-01-09', 0, 90);
INSERT INTO t1 (cid, d,i,v) VALUES (2,'2001-01-04', 1, 35);
CREATE TABLE t2 (cid INT, d DATE, i INT, av2 FLOAT, av3 FLOAT);
INSERT INTO t2 (cid, d,i) VALUES (1,'2001-01-07', 0);
INSERT INTO t2 (cid, d,i) VALUES (1,'2001-01-08', 1);
INSERT INTO t2 (cid, d,i) VALUES (2,'2001-01-08', 0);
INSERT INTO t2 (cid, d,i) VALUES (2,'2001-01-09', 1);
av2
和av3
是我想要上次2
或3
次交易的平均值的列。所以我需要一个更新声明(真正的两个声明,一个用于av2,一个用于av3)来说“当这个客户在这个日期进来时,他们是否独自进入,他们最近x次采购的平均值是多少。” / p>
所以结果数据应该是:
cid d i av2 av3
1 2001-01-07 0 55 40
1 2001-01-08 1 35 40
2 2001-01-08 0 null null
2 2001-01-08 1 35 35
我最接近的是:
UPDATE t2 SET av=(
SELECT AVG(tcol)
FROM (
SELECT v AS tcol FROM t1 LIMIT 2
) AS tt);
似乎正朝着正确的方向发展(限制2是来自av列的2
或3
。但这只是平均x次之前的购买(无论客户还是布尔值)。只要我输入WHERE子句来链接数据,它就会扼杀:
UPDATE t2 SET av=(
SELECT AVG(tcol)
FROM (
SELECT v AS tcol FROM t1 WHERE t1.d<t2.d and t1.i=t2.i LIMIT 2
) AS tt);
有什么想法吗?我正在尝试做什么名称?我需要以不同的方式描述这个吗?有什么建议吗?
谢谢, 菲利普
答案 0 :(得分:1)
试试这个 -
SET @r = 0;
SET @cid = NULL;
SET @i = NULL;
UPDATE t2 JOIN (
SELECT t.cid, t.d, t.i, AVG(IF(t.r < 3, t.v, NULL)) av2, AVG(IF(t.r < 4, t.v, NULL)) av3 FROM (
SELECT t.*, IF(@cid = t.cid AND @i = t.i, @r := @r + 1, @r := 1) AS r, @cid := t.cid, @i := t.i FROM (
SELECT t2.*, t1.v FROM t2
JOIN t1
ON t1.cid = t2.cid AND t1.d < t2.d AND t1.i = t2.i
ORDER BY t2.cid, t2.i, t1.d DESC
) t
) t
GROUP BY t.cid, t.i, t.d
) t
ON t2.cid = t.cid AND t2.i = t.i AND t2.d = t.d
SET t2.av2 = t.av2, t2.av3 = t.av3;
SELECT * FROM t2;
+------+------------+------+------+------+
| cid | d | i | av2 | av3 |
+------+------------+------+------+------+
| 1 | 2001-01-07 | 0 | 55 | 40 |
| 1 | 2001-01-08 | 1 | 35 | 30 |
| 2 | 2001-01-08 | 0 | NULL | NULL |
| 2 | 2001-01-09 | 1 | 35 | 35 |
+------+------------+------+------+------+
注意:强> cid = 1,d = 2001-01-08,i = 1的值av3应为30,rigth? ......不是40。