我有一个类似于以下内容的表:
W1 W2 w3
Gold 10 2 3
Silver 3 1 1
但我需要一个结果:
W1 W2 w3
Gold 10 12 15
Silver 3 4 5
有什么方法可以得到那个结果吗?
我的SQL查询:
SELECT
week1=[1],week2=[2],week3=[3]
FROM
(
SELECT
[week]=DATEPART(ISO_WEEK,ta.enddate),ta.price
FROM
table1 ta where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
SUM(price) FOR week IN (
[1],[2],[3])
) piv
答案 0 :(得分:0)
在旋转数据之前计算运行总计
SELECT element,
week1=[1],week2=[2],week3=[3]
FROM
(
SELECT [week] = DATEPART(ISO_WEEK,ta.enddate),
price = sum(ta.price)Over(Partition by element Order by enddate),
element
FROM table1 ta
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
SUM(price) FOR week IN ( [1],[2],[3])
) piv
旧版本
SELECT element,
week1=[1],week2=[2],week3=[3]
FROM
(
SELECT [week] = DATEPART(ISO_WEEK,ta.enddate),
cs.price,
element
FROM table1 ta
cross apply(select sum(price) from table1 tb
where ta.element = tb.element and ta.enddate >= tb.enddate ) cs (price)
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
SUM(price) FOR week IN ( [1],[2],[3])
) piv