我正在处理查询以创建view
,其中需要包含客户的汇总销售数据,但新的销售数据会添加为列而不是行。在表格中,每行代表customer ID
,列为" week of 20160808
"。有没有办法创建查询dynamically
捕获添加的新列而不对列名进行硬编码(20160801+20160808+20160815
)?
答案 0 :(得分:0)
我会做像
这样的事情SELECT Year(DateOfSale), CustomerId, [1] ... [52] FROM YourDataTable
Pivot(sum(sales) FOR WeekNumber IN (1..52)) as Pivoted
它不会为您提供最佳命名列,但您可以在显示它时整理它。
答案 1 :(得分:0)
我不知道XQuery是否允许在视图中使用。如果是,您可以试试这个:
select CustId,
(select * from MyTable where CustId = x.CustId for xml path('row'), type).value('sum(row/*[not(self::CustId)])','float')
from MyTable x
例如表格
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
)
结果是
CustId
----------- ----------------------
1 6
2 6,76
3 888,88
和表格
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
)
相同的查询将获得
CustId
----------- ----------------------
1 10
2 6,76
3 1888,88