带有AGGREGATE更新的SQLite3 RECURSIVE

时间:2015-11-04 21:56:32

标签: recursion sqlite average

阅读并尝试在没有启发的情况下参加之前关于这个主题的讨论。下面的SQL代码已经嵌入了评论。 Windows 7上的SQLite版本3.9.1 2015-10-16 17:31:12 UPDATE中从属于SET子句的子查询不会递归 - 传递单个标量值。或者我有一个递归崩溃?

// In which we investigate recursive update
.mode list
SELECT 'Create and populate tables of detail and to hold aggregate';
DROP TABLE IF EXISTS temp.detail;
DROP TABLE IF EXISTS temp.average;
CREATE TEMP TABLE detail  (rowid INTEGER PRIMARY Key AUTOINCREMENT, 
   grp INTEGER,atom FLOAT);
INSERT INTO detail (grp,atom) VALUES (2,2);
INSERT INTO detail (grp,atom) VALUES (2,4);
INSERT INTO detail (grp,atom) VALUES (1,3);
INSERT INTO detail (grp,atom) VALUES (1,5);
INSERT INTO detail (grp,atom) VALUES (3,1);
INSERT INTO detail (grp,atom) VALUES (3,3);
SELECT * FROM detail;
CREATE TEMP TABLE average (rowid INTEGER PRIMARY KEY AUTOINCREMENT, avrg FLOAT);
INSERT INTO average (avrg) VALUES (1.0);
INSERT INTO average (avrg) VALUES (1.0);
INSERT INTO average (avrg) VALUES (1.0);
.mode column average
.mode column detail
.header on
.width 7
SELECT avrg as Average FROM average;
SELECT 'SELECT produces three rows';
with recursive loop(bid) as (Values(1) union all
    select bid + 1 from loop LIMIT 3)
    SELECT AVG(atom) AS Average  from detail 
    where grp IN loop GROUP BY grp;

Average
-------
4.0
3.0
2.0


SELECT 'Within SET clause, SELECT produces one scalar result';
with recursive loop(bid) as (Values(1) union all
    select bid + 1 from loop LIMIT 3)
    UPDATE average SET avrg =
    (SELECT AVG(atom) from detail
    WHERE grp in loop GROUP BY grp HAVING grp IN loop)
    where rowid in loop;
SELECT 'Single SET result populates all target rows';
SELECT avrg AS Average from average;

Average
-------
4.0
4.0
4.0

好的,一天之后,所以我试图将循环控制表关联到子查询中。

with recursive loop(grp) as (Values(1) union all
select grp + 1 from loop LIMIT 3)
UPDATE average SET avrg =
(SELECT AVG(atom) from detail, loop
WHERE detail.grp = loop.grp 
GROUP BY detail.grp)
where rowid IN loop;
SELECT avrg AS Average FROM average;

平均

4.0 4 4 或者我试过这个......

    sqlite> with recursive loop(grp) as (Values(1) union all
   ...>     select grp + 1 from loop LIMIT 3)
   ...>     UPDATE average SET avrg =
   ...>     (SELECT AVG(atom) from detail, loop
   ...>     GROUP BY loop.grp)
   ...>     where rowid IN loop;
   sqlite> SELECT avrg AS Average FROM average;

平均

3.0 3.0 3.0 哪个不同但仍然不受欢迎。 我需要的是来自INSERT变体......的行为......

sqlite> DROP TABLE average;
sqlite> CREATE TEMP TABLE average (rowid INTEGER PRIMARY KEY AUTOINCREMENT, 
avrg FLOAT);
sqlite> INSERT INTO average (avrg)
...>     with recursive loop(grp) as (Values(1) union all
...>     select grp + 1 from loop LIMIT 3)
...>     SELECT AVG(atom) from detail NATURAL JOIN loop
...>     GROUP BY grp;
sqlite> SELECT avrg AS Average FROM average;

平均

4.0 3.0 2.0

0 个答案:

没有答案