2017-09-19 50 views

回答

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 
1

如果您需要構建它在Excel中,然後用下面兩個公式:

AVERAGEIF

SUMIF

這些公式將採取的護理空值自動。

4

另一種選擇是用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 
+0

完美!謝謝約翰。 – Paul

+0

@Paul樂於助人 –

0

首先,你需要逆轉置數據後進行彙總

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 

結果

Dept       Sum          Agv 
------------------------------ --------------------------------------- --------------------------------------- 
Medicine      917.6700        76.472500 
Non-Medicine     1502.6200        88.389411