【问题标题】:SQLite showing a percentage of a SUM from total SUMSQLite 显示总和中总和的百分比
【发布时间】:2022-01-09 03:46:13
【问题描述】:

我有一张桌子,上面有一些费用。我想选择类别(不重复)、每个类别的费用总和,以及这个总和占总和的百分比。

前两件事我成功了,但总和我没有。我想是因为 GROUP BY。

SELECT SUM(Value), [Expense Category]
FROM expenses
WHERE Year = 2021
GROUP BY [Expense Category]
ORDER BY SUM(Value) DESC

我可以在这个 SELECT 中包含总和吗?怎么样?

谢谢!

【问题讨论】:

  • MySql 与 SQLite 不同。仅标记您使用的数据库。
  • 对不起,我修改了标签和标题。

标签: sqlite group-by sum window-functions


【解决方案1】:

在这种情况下,您可以使用窗口功能

SELECT DISTINCT SUM(Value) over(partition by [Expense Category])/SUM(Value), [Expense Category]
FROM expenses
WHERE Year = 2021
GROUP BY [Expense Category]

或者只是在子查询中计算总和

SELECT [Expense Category], sum_/total_sum
(
    SELECT SUM(Value) sum_, [Expense Category]
    FROM expenses
    WHERE Year = 2021
    GROUP BY [Expense Category]
    ORDER BY SUM(Value) DESC
) a 
CROSS JOIN (SELECT SUM(Value) total_sum FROM expenses) b

【讨论】:

  • 谢谢,但第一个结果不是我想要的。 :(
  • 第二个是报错。是因为我使用 SQLite?非常抱歉造成误解。
【解决方案2】:

您可以在查询中使用窗口函数SUM() 来计算表的总数value

SELECT [Expense Category],
       SUM(Value) sum_value, 
       100.0 * SUM(Value) / SUM(SUM(Value)) OVER () percentage
FROM expenses
WHERE Year = 2021
GROUP BY [Expense Category]
ORDER BY SUM(Value) DESC;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多