我是sqlite世界的新手,我正在编写一个用于创建成分收件人的应用程序,我需要为收件人创建成分标签。
我有这张桌子tb_composizioni
id id_ricetta id_ingrediente id_ricetta_livello qty
"1" "1" "51" "0" "1000.0"
"2" "1" "3" "0" "400.0"
"3" "2" "186" "0" "640.0"
"4" "2" "94" "0" "30.0"
"5" "2" "51" "0" "30.0"
"6" "3" "0" "2" "1000.0"
"7" "3" "0" "1" "100.0"
我想创建一个“物料清单” 收件人3由1000gr的recipie 2和100gr的recipie 1组成
这是我的查询
WITH RECURSIVE
lista_ingredienti(id_ricetta,id_ingrediente,qty,level) AS (
VALUES('3',0,0,0)
UNION ALL
SELECT tb_composizioni.id_ricetta_livello, tb_composizioni.id_ingrediente, tb_composizioni.qty, lista_ingredienti.level+1
FROM tb_composizioni JOIN lista_ingredienti ON tb_composizioni.id_ricetta=lista_ingredienti.id_ricetta
ORDER BY 3 desc
)
SELECT id_ricetta, id_ingrediente , qty FROM lista_ingredienti
结果是:
id_ricetta id_ingrediente qty
"3" "0" "0"
"2" "0" "1000.0"
"0" "186" "640.0"
"1" "0" "100.0"
"0" "51" "71.42"
"0" "3" "28.57"
"0" "51" "30.0"
"0" "94" "30.0"
我想获得成分的标签,所以我必须按照总数重新缩放。 recipie 1的总数是1400gr,recipie 2的总数是700gr。 如果我在收件人3中重新缩放收件人1的数量,那么因子是100/1400 = 0.0714,第二次重新缩放是 收件人2,因此因子是1000/700 = 1.4285 可以像这样重新调整表格:
id_ricetta id_ingrediente qty
"3" "0" "0"
"2" "0" "1000.0"
"0" "186" "914.2"
"1" "0" "100.0"
"0" "51" "71.4"
"0" "3" "28.5"
"0" "51" "42.8"
"0" "94" "42.8"
和这样的成分的最终标签:
id_ricetta id_ingrediente qty
"3" "0" "0"
"0" "186" "914.2"
"0" "51" "114.2"
"0" "94" "42.8"
"0" "3" "28.5"
这是.dump文件sql:
CREATE TABLE "tb_composizioni" (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`id_ricetta` INTEGER NOT NULL,
`id_ingrediente` INTEGER NOT NULL,
`id_ricetta_livello` INTEGER,
`qty` REAL DEFAULT 0,
);
INSERT INTO `tb_composizioni` VALUES (1,1,51,0,1000.0);
INSERT INTO `tb_composizioni` VALUES (2,1,3,0,400.0);
INSERT INTO `tb_composizioni` VALUES (5,2,186,0,640.0);
INSERT INTO `tb_composizioni` VALUES (9,2,94,0,30.0);
INSERT INTO `tb_composizioni` VALUES (15,3,0,2,1000.0);
INSERT INTO `tb_composizioni` VALUES (16,3,0,1,100.0);
INSERT INTO `tb_composizioni` VALUES (17,2,51,0,30.0);