SQLite 中行的不同计算

Varying Calculations for Rows in SQLite

我的SQLtable是这样设置的:

修饰符决定了对总分的影响。即

理想情况下,我想制作 table 的:

我一辈子都无法让它发挥作用。我最接近的是下面的代码,它为每个父键输出一行,为每个修饰符输出一列。但是,尽管这些语句都产生了我想要的独立值,但每一列都填充了一个值。

SELECT table.parent, t1.one, t1.two, t1.three
FROM
table
LEFT JOIN

(SELECT 
(SELECT ((sum(points1)+sum(points2))*0.1) FROM table WHERE (modifier = "modifier one") GROUP BY key) as 'one', 
(SELECT ((sum(points1)+sum(points2))*0.2) FROM table WHERE (modifier = "modifier two") GROUP BY key) as 'two',
(SELECT ((sum(points1)+sum(points2))*0.7) FROM table WHERE (modifier = "modifier three") GROUP BY key) as 'three'
) t1

GROUP BY table.parent

您可以使用条件聚合来完成:

SELECT parent,
       SUM((points1 + points2) * CASE WHEN modifier = 'modifier one' THEN 0.1 ELSE 0 END) one,
       SUM((points1 + points2) * CASE WHEN modifier = 'modifier two' THEN 0.2 ELSE 0 END) two,
       SUM((points1 + points2) * CASE WHEN modifier = 'modifier three' THEN 0.7 ELSE 0 END) three
FROM tablename
GROUP BY parent;

或者,使用 TOTAL() 聚合函数:

SELECT parent,
       0.1 * TOTAL((points1 + points2) * (modifier = 'modifier one')) one,
       0.2 * TOTAL((points1 + points2) * (modifier = 'modifier two')) two,
       0.7 * TOTAL((points1 + points2) * (modifier = 'modifier three')) three
FROM tablename
GROUP BY parent;

或者,如果您的 SQLite 版本是 3.30.0+,使用 FILTER 子句:

SELECT parent,
       0.1 * TOTAL(points1 + points2) FILTER (WHERE modifier = 'modifier one') one,
       0.2 * TOTAL(points1 + points2) FILTER (WHERE modifier = 'modifier two') two,
       0.7 * TOTAL(points1 + points2) FILTER (WHERE modifier = 'modifier three') three
FROM tablename
GROUP BY parent;