sql server 2008 - SQL Average By Column Name -


i have following t-sql , having struggle trying find out average beginning of year (january) current month. example, should show average january august column. don't know how avg column names until specific month (current month):

select     [customer], category,     [1] january, [2] febrary, [3] march,     [4] april, [5] may, [6] june,     [7] july, [8] august, [9] september,     [10] october, [11] november, [12] december      (select          month(received) my_month, [customer], category                data                 year(received) = '2017') t pivot      (count(my_month) my_month in([1], [2], [3], [4], [5],[6],[7],[8],[9],[10],[11],[12])) p 

just use conditional aggregation:

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

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -