按列+ COUNT(*)分组,如何获得每个组合的平均数?

时间:2011-08-05 23:14:23

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

我有以下(简化)查询:

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.
  3. 所以我想总结每个组合的数量并除以出现次数。

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

    提前谢谢。

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分: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