【问题标题】:SQL show individual results as % of total [duplicate]SQL将单个结果显示为总数的百分比[重复]
【发布时间】:2021-11-30 03:12:44
【问题描述】:

希望有人能帮我解答这个问题。

我在名为 t_customerdata 的表中有以下数据集:

Customer Balance
John $100
Paul $150
Linda $50
Karen $95

我想要在同一张表中显示每个人占总余额的百分比。

所以,基本上,我的目标是让表格看起来像这样:

Customer Balance %ofTotal
John $100 25.3164
Paul $150 37.9746
Linda $50 12.6582
Karen $95 24.0506

我已经尝试了下面的代码,有点天真地希望它可以工作,但它并没有因为 SQL 也强制我按余额分组,这意味着 calc 总是返回 100%:

select
customer,
balance / sum(balance) as [%ofTotal]
from t_customerdata
group by
customer,
balance

【问题讨论】:

  • 你的数据库是什么?余额列是字符串吗?
  • 余额是双倍的。我正在使用我的公司为数据挖掘目的创建的数据立方体,并在共享驱动器位置读取 Excel 电子表格。它使用 CubeSQL 的一种形式,因此我没有正常的 SQL CTE 或窗口函数

标签: sql select


【解决方案1】:

您可以使用窗口函数。例如:

select *, 100.0 * balance / sum(balance) over() from t_customerdata

【讨论】:

  • 抱歉应该澄清一下,我使用的数据挖掘软件使用的是 CubeSQl 的形式,并且我没有通常的窗口或 CTE 功能可用
  • 如果您的数据库引擎没有实现窗口函数,那么@Steven 的答案是最好的。另一方面,如果 CubeSQL 在 SQLite 之上运行,那么您确实可以访问窗口函数。
【解决方案2】:

你可以这样做:

select *, balance*100.0 / (select sum(balance) from t_customerdata)
from t_customerdata


custommer   balance (No column name)
john    100 25.316455696202
paul    150 37.974683544303
Linda   50  12.658227848101
karen   95  24.050632911392

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2013-11-17
    相关资源
    最近更新 更多