SQL平均行数和列同时 - 如矩阵平均值

时间:2017-09-19 14:25:52

标签: sql sql-server excel tsql

我有一张这样的桌子 -
enter image description here

我想按部门分组以获得具有多行的四列的总数和平均值。输出应该看起来像 -
enter image description here
有人可以帮忙!

4 个答案:

答案 0 :(得分:5)

另一种选择是使用CROSS APPLY

Select A.Dept     
      ,MonthTotal = sum(B.value)
      ,MonthAvg   = avg(B.value)
 From YourTable A
 Cross Apply ( values (month1)
                     ,(month2)
                     ,(month3)
                     ,(month4)
             ) B(value)
 Group By A.Dept

答案 1 :(得分:1)

如果需要在Excel中构建它,请使用以下两个公式:

AVERAGEIF

SUMIF

这些公式会自动处理空值。

答案 2 :(得分:0)

使用GROUP BY

  SELECT SUM(month1 + month2 + month3 + month4) AS MonthTotal,
         SUM(month1 + month2 + month3 + month4)/(COUNT(*) * 4) AS MonthAvg,
         dept
  FROM your_table
  GROUP BY dept

答案 3 :(得分:0)

首先,您需要在执行聚合后对数据进行取消隐藏

df %>%
mutate(month = format(date, "%m"), year = format(date, "%Y")) %>%
group_by(month, year) %>%
summarise(total_sum = sum(value))

结果

declare @table table (Dept varchar(30), Month1 decimal(16,4), Month2 decimal(16,4), Month3 decimal(16,4), Month4 decimal(16,4))
Insert @table (Dept, Month1, Month2, Month3,Month4) values
 ('Medicine'        , 80.06     ,80.0709    ,80.0709    ,80.8153)
,('Medicine'        , 61.64     ,null       ,81.8364    ,79.1241)
,('Medicine'        , 48.34     ,79.0159    ,null       ,null)
,('Medicine'        , null      ,87.5137    ,83.7288    ,75.454)
,('Non-Medicine'    , 85.13     ,89.36      ,89.36      ,89.36)
,('Non-Medicine'    , 82.21     ,91.2732    ,91.334     ,null)
,('Non-Medicine'    , 106.19    ,NULL       ,80.3801    ,82.2787)
,('Non-Medicine'    , 94.44     ,75.0055    ,75.4232    ,75.4335)
,('Non-Medicine'    , 119.77    ,87.6069    ,88.0649    ,null)

Select 
Dept
,Sum(Sales) 
,Avg(Sales)
FROM (
SELECT 
     Dept 
    ,Month 
    ,Sales
FROM
(
 SELECT 
     Dept
    ,Month1
    ,Month2
    ,Month3
    ,Month4
 FROM @table
) p  UNPIVOT (Sales For Month in (Month1,Month2,Month3,Month4) ) U
WHERE Sales Is not null
) x 

Group by 
Dept