【问题标题】:Group by columns + COUNT(*), how to get the average count for every combination?按列 + COUNT(*) 分组,如何获得每个组合的平均计数?
【发布时间】:2011-10-21 06:28:07
【问题描述】:

我有以下(简化的)查询:

SELECT     ResolvedBy, COUNT(*) AS Count, fiCategory, fiSubCategory, fiSymptom
FROM         tContact
WHERE     (ResolvedBy IS NOT NULL)
GROUP BY ResolvedBy, fiCategory, fiSubCategory, fiSymptom
ORDER BY Count DESC

现在我需要fiCategory, fiSubCategory, fiSymptom 的每个组合的平均计数作为列。该怎么做?

例如:

ResolvedBy    Count    fiCategory    fiSubCategory    fiSymptom    Average
    1           50         1              2             3            40
    2           30         1              2             3            40
    3           40         1              2             3            40
    1           20         2              3             4            30
    2           40         2              3             4            30

在示例中是 fiCategory、fiSubCategory 和 fiSymptom 的两种组合:1,2,32,3,4。因此,计算了两个平均值:

  1. 50+30+40 / 3 = 40
  2. 20+40 / 2 = 30。

所以我想将每个组合的计数相加并除以出现次数。

编辑:该示例是对所需查询结果的提取。计数是每个ResolvedBy 的此组合的所有出现的总和。

提前谢谢你。

【问题讨论】:

  • 为了帮助确定解决方案,您如何得出平均值?
  • 您是指使用显示数据的平均值吗?即,fiCategory 的平均值为 (1+1+1+2+2)/5 = 1.4?
  • 这也可能有助于查看您期望输出的样子。
  • 在示例中是 fiCategory、fiSubCategory 和 fiSymptom 的两种组合:1,2,3 和 2,3,4。因此计算出两个平均值:1.combi => 50+30+40/3 和 2.combi => 20+40/2。所以我想总结每个组合的计数并除以出现次数。

标签: sql sql-server sql-server-2005 group-by


【解决方案1】:
Select ResolvedBy, [Count], fiCategory, fiSubCategory, fiSymptom
    , Avg(Z.Count) Over( Partition By fiCategory, fiSubCategory, fiSymptom ) As AvgByGrp
From    (
        Select ResolvedBy, Count(*) As [Count], fiCategory, fiSubCategory, fiSymptom
        From tContact 
        Group By ResolvedBy, fiCategory, fiSubCategory, fiSymptom
        ) As Z

Order By Z.Count Desc

【讨论】:

  • 没有列Count,如果我将其更改为COUNT(*),我会得到一个异常:“不能在用于分组的表达式中使用聚合或子查询 GROUP BY 的列表子句”
  • @Tim Schmelter - 嗯..您必须使用子查询来完成。将调整以进行演示。
  • 尝试从group by 中删除count。我为托马斯添加了它,认为这是一个基于他在SELECT 中的内容的专栏,但我可能做得比好不好:(
  • @Abe Miessler - 我相信您必须首先在派生表中运行计数才能获得每个组的计数。然后,您可以针对该结果计算平均值。
  • @Abe:也感谢您的工作和时间。它给出了正确的结果。令人印象深刻的是,人们可以在不知道确切要求和数据的情况下理解和解决这个问题。
【解决方案2】:

试试这个:

SELECT main.ResolvedBy, COUNT(*) AS Count, 
    main.fiCategory, main.fiSubCategory, main.fiSymptom, average
FROM tContact main
JOIN (SELECT COUNT(*)/count(distinct ResolvedBy) as average,
      fiCategory, fiSubCategory, fiSymptom group by 2,3,4) x
        on x.fiCategory = main.fiCategory
        and x.fiSubCategory = main.fiSubCategory
        and x.fiSymptom = main.fiSymptom
WHERE main.ResolvedBy IS NOT NULL
GROUP BY 1, 3, 4, 5
ORDER BY 2 DESC

【讨论】:

  • 我得到一个“每个 GROUP BY 表达式必须包含至少一个不是外部引用的列”。
猜你喜欢
  • 2021-04-03
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
相关资源
最近更新 更多