【问题标题】:Multiple row filter and Calculate percentage多行过滤器和计算百分比
【发布时间】:2021-01-13 07:10:17
【问题描述】:

enter image description here我是 SQL 新手。我正在研究一个需要过滤然后计算百分比的数据库。下面是示例表。 后续步骤:

  • 第一个过滤器列性质只有创建、审查和坐标。
  • 按列、团队、TeamTeam、客户分组并汇总小时数。
  • 然后根据上述组计算Creat、Review和Coordinate的百分比。
  • 最后我需要输出列 Team、TeamTeam、Client、%Create、%Review 和 %Coordinate。

提前致谢。 enter image description here

【问题讨论】:

  • 给定您的样本数据,结果表应该是什么样子?
  • 团队 TeamTeam 客户坐标 创建审核 Sum_Hours 审核 % 坐标 % 创建 % 团队 1 团队 BB ABC1 3 1 9 0% 33% 11% 团队 1 团队 CC ABC1 2 2 100% 0% 0% 团队 1团队 DD ABC1 4 0% 0% 0% 团队 2 团队 BB ABC2 7 27 26% 0% 0% 团队 2 团队 CC ABC2 6 16 0% 0% 38% 团队 2 团队 DD ABC2 8 8 0% 100% 0% 团队第 3 队 BB ABC3 19 17 13 64 20% 30% 27% 第 3 队 CC ABC3 14 18 32 56% 44% 0% 第 3 队 DD ABC3 12 28 0% 0% 43%
  • 我在主查询中添加了输出图像。谢谢

标签: sql sql-server sum pivot percentage


【解决方案1】:

您可以使用where 子句进行过滤,然后使用group bysum。要计算百分比,直接的方法是avg() 和条件聚合。

select team, client, sum(hours) sum_hours,
    avg(case when nature = 'create'     then 100.0 else 0 end) percent_create,
    avg(case when nature = 'review'     then 100.0 else 0 end) percent_review,
    avg(case when nature = 'coordinate' then 100.0 else 0 end) percent_coordinate
from mytable
where nature in ('create', 'review', 'coordinate')
group by team, client

【讨论】:

  • Msg 8114,级别 16,状态 5,第 1 行将数据类型 nvarchar 转换为数字时出错。我正在尝试执行的总和收到此错误。如何更改数据类型?我使用 "sum(cast([Hours]as decimal)) 作为 Sum_Hours,
  • 我也试过“SUM(CAST([Hours] AS numeric)) as sum_hours”不起作用
  • 干得好!我喜欢计算组百分比的方式。酷
  • @Rock 使用 try_convert(numeric(12), [hours]) 如果列包含无法转换的内容,它将返回 null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-22
  • 2011-06-01
相关资源
最近更新 更多