【问题标题】:Varying Calculations for Rows in SQLiteSQLite 中行的不同计算
【发布时间】:2022-01-27 23:36:27
【问题描述】:

我的 SQL 表是这样设置的:

  • 键(主键)
  • 父键(一个父键的多个主键)
  • 点 1
  • 点 2
  • 修饰符

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

  • 修改器 A - 总点数 =(点 1 + 点 2)*0.1
  • 修改器 B - 总点数 =(点 1 + 点 2)*0.2
  • 修饰符 C - 总分 = (points 1 + points 2)*0.7

理想情况下,我想制作一张表格:

  • 父键
  • 该键的总修改点数(例如 100 * 0.2 + 150 * 0.5 + 180 * 0.7)

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

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

【问题讨论】:

    标签: sql sqlite group-by case calculated-columns


    【解决方案1】:

    您可以使用条件聚合来做到这一点:

    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;
    

    【讨论】:

    • 一切正常。我正在使用最后一个解决方案,因为我觉得它是最优雅的,谢谢你的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2011-08-24
    • 1970-01-01
    • 2023-03-20
    • 2020-08-27
    相关资源
    最近更新 更多