【问题标题】:Using an aggregate for totals using Rollup使用汇总对总计使用聚合
【发布时间】:2018-09-01 03:40:13
【问题描述】:

我正在尝试使用汇总,并想了解是否有一种方法可以在不使用子查询、CTE 或临时表的情况下实现这一目标。这是我的代码:

    select coalesce(Answer,case Grouping_ID(Answer) when 1 then 'Total' end) as Answer
    , Count(*) as CSAT_Count
    , Case Answer
        when 'Average' then 2*count(*)
        when 'Outstanding' then 3*Count(*)
        when 'Unsatisfactory' then 1*Count(*) 
      end as CSAT_Score
from CSAT_Table
Where Empl_ID = 98
Group by Answer
with rollup

结果如下:

     Answer               CSAT_Count    CSAT_Score
    ----------------------------------------------
     Average              13            26
     Outstanding          126           378
     Unstatisfactory      6             6
     Total                145           NULL

我想让 CSAT_Score 中返回的 NULL 反映分数的总和,但我在想,因为分数依赖于 COUNT(*) 来计算,我无法让 Rollup 为我,因为我不能按聚合分组。

就像我上面说的,我知道存储计数结果的子查询、CTE 或 Temp 表会起作用,但由于我是使用 Rollup 的新手,所以我想看看是否还有其他可以做的事情使这项工作发挥作用的功能。

谢谢

【问题讨论】:

  • 只是好奇:为什么您如此强烈地反对使用 CTE 或临时表的解决方案?
  • @SQL_M 因为我刚开始使用 Rollup,所以我想看看我是否可以用这个函数做其他事情来完成这项工作。
  • 据我所知,您无法使用with rollup 执行此操作,因此派生表路由是您最好的选择。
  • @SQL_M - 我不反对,只是想确保我了解 Rollup 的工作原理。我确切地知道如何使用 CTE/Temp 表来做到这一点。

标签: sql sql-server tsql sql-server-2012 ssms


【解决方案1】:

此版本的脚本与 rollup 一起使用。 (顺便说一句,它产生相同的结果)

  select coalesce(Answer,case Grouping_ID(Answer) when 1 then 'Total' end) as Answer
    , Count(*) as CSAT_Count
    , Sum(Case Answer
        when 'Average' then 2
        when 'Outstanding' then 3
        when 'Unsatisfactory' then 1
      end) as CSAT_Score
from CSAT_Table
Where Empl_ID = 98
Group by Answer
with rollup

【讨论】:

  • 就是这样!!谢谢!!
猜你喜欢
  • 2015-12-25
  • 2021-10-27
  • 2022-01-27
  • 2012-03-08
  • 2015-02-02
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 2019-05-05
相关资源
最近更新 更多