简体   繁体   中英

SQL Query to Aggregate Growing Columns

I'm working on a query to create a view which needs to contain aggregated sales data for customers but new sales data is added as columns instead of rows. In the table, each row represents a customer ID and columns are " week of 20160808 ". Is there a way to create the query to dynamically capture the new columns added without hard coding the column names ( 20160801+20160808+20160815 )?

I would do something like

SELECT Year(DateOfSale), CustomerId, [1] ... [52] FROM YourDataTable 
Pivot(sum(sales) FOR WeekNumber IN (1..52)) as Pivoted

It won't give you the best named columns, but you could tidy that up when you display it.

I dont know if XQuery allowed in views. If yes, you may try this:

select CustId,
  (select * from MyTable where CustId = x.CustId for xml path('row'), type).value('sum(row/*[not(self::CustId)])','float')
from MyTable x

For example for table

with MyTable(CustId, week0, week1, week2) as (
  select 1,  1,2,3
  union all
  select 2,  1.50, 2.25, 3.01
  union all
  select 3,  111.11, 222.22, 555.55
)

the the result is

CustId      
----------- ----------------------
1           6
2           6,76
3           888,88

and for table

with MyTable(CustId, week0, week1, week2, week3) as (
  select 1,  1,2,3,4
  union all
  select 2,  1.50, 2.25, 3.01, 0
  union all
  select 3,  111.11, 222.22, 333.33, 1000
)

same query will get

CustId      
----------- ----------------------
1           10
2           6,76
3           1888,88

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM