【问题标题】:SQL - Percentage countSQL - 百分比计数
【发布时间】:2013-02-16 23:45:05
【问题描述】:

我有一个名为 URP_PROJECT 的表,一个名为 ts_title 的列。 ts_title 列下有不同的记录数据。如何计算 ts_title 下的每条记录的百分比? 百分比列根据下面的 SQL 查询添加。

我开始:

选择 ts_title

COUNT (ts_title) AS 百分比

帮我继续​​,谢谢

【问题讨论】:

  • 你使用的是什么数据库 MS SQL Server、MySQL、Oracle?
  • SSRS - SQL Server 报告服务
  • 其余列是什么。 ts_title 是 varchar 还是 int?
  • 我很困惑。 count(ts_title) 将计算 ts_title 不为空的行数。
  • 举个很好的例子:在Fruits栏下,有水果名称的列表,甚至还有重复的水果名称。我只想计算每种水果的百分比。

标签: sql sql-server-2008


【解决方案1】:

这可能会给你想要的东西

  select ts_title, 
         count(1) * 100.0 / (select count(1) from upr_project)
 from upr_project
group by ts_title

乘以 100.0 将其转换为浮点数以获得更准确的百分比。

【讨论】:

  • 谢谢!在百分比的帮助下转换为浮点数加到 100。
【解决方案2】:

另一种解决方案是使用窗口函数:

select ts_title,
       100.0 * (up.cnt*1.0 / (sum(up.cnt) over (partition by 1)))
from 
(
  select ts_title, count(*) as cnt
  from upr_project
  group by ts_title
) up

【讨论】:

  • 当您有一个使用 GROUPING SETS、ROLLUP 或 CUBE 的“总计”行时,此解决方案也适用。您只需将 up.cnt 乘以 2.0 而不是 1.0 即可计算“总计”行的额外数量。
【解决方案3】:

试试这个

SELECT ts_title,
(count(ts_title) * 100 / (SELECT count(*) FROM URP_PROJECT)) as percentage 
FROM URP_PROJECT Group BY ts_title

【讨论】:

    【解决方案4】:

    您好,我猜您正在寻找整个表格中 ts_title 记录的百分比。如果是这种情况,这将对您有所帮助

    DECLARE @ActualCount INT
    
    select @ActualCount = COUNT(*) from urp_project
    
    
    select ts_title
      ,(Count(ts_title)/ @ActualCount )* 100 AS Percentage       
    from urp_project
    group by ts_title;
    

    【讨论】:

      【解决方案5】:

      可能是这样的:

      SELECT
        ts_title,
        COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () AS percentage
      FROM URP_PROJECT
      GROUP BY ts_title
      

      有用的阅读:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多