SQL按列名称平均值

时间:2017-08-20 20:28:13

标签: sql sql-server-2008 tsql

我有以下T-SQL并且正在努力找出从年初(1月)到当月的平均值。例如,它应该显示1月到8月的平均值作为列。我不知道如何从列名获取AVG直到特定月份(当月):

select
    [Customer], category,
    [1] AS January, [2] AS Febrary, [3] AS March,
    [4] AS April, [5] AS May, [6] AS June,
    [7] AS July, [8] AS August, [9] AS September,
    [10] AS October, [11] AS November, [12] AS December 
from
    (select
         month(received) as my_month, [Customer], category 
     from
         Data 
     where 
         year(Received) = '2017') AS t
pivot 
    (count(my_month) for my_month IN([1], [2], [3], [4], [5],[6],[7],[8],[9],[10],[11],[12])) as p

2 个答案:

答案 0 :(得分:2)

只需使用条件聚合:

select customer, category,
       sum(case when month(received) = 1 then 1 else 0 end) as jan,
       sum(case when month(received) = 2 then 1 else 0 end) as feb,
       . . .,
       sum(case when month(received) <= 1 then 1 else 0 end) as thru_jan,
       sum(case when month(received) <= 2 then 1 else 0 end) as thru_feb,
       . . .
       sum(case when month(received) >= 1 and month(received) <= month(getdate()) then 1 else 0 end) as uptonow
from data
where received >= '2017-01-01' and received < '2018-01-01'
group by customer, category;

答案 1 :(得分:0)

对我来说,看起来你是从一个完全错误的立场接近这个。这样的事情应该返回当前年份的平均值,直到按客户和类别分组的当前月份开始:

SELECT AVG(received), Customer, Category
  FROM Data
  WHERE YEAR(Received) = 2017 
    AND MONTH(Received) < MONTH(GETDATE())
  GROUP BY Customer, Category