T-sql:得到列的和

时间:2017-07-05 14:08:07

标签: sql tsql reporting-services

我有一个类似于以下内容的表:

          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.id
    FROM
    table1 ta where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
    SUM(id) FOR week IN ( 
        [1],[2],[3])
) piv

3 个答案:

答案 0 :(得分:0)

这样做你想要的吗?

select t.??, t.w1, (t.w1 + t.w2) as w2, (t.w1 + t.w2 + t.w3) as w3
from table1 t;

我不知道第一列的名称是什么,所以我只使用??

答案 1 :(得分:0)

有人想到,因为您使用Reporting Services标记了此问题。最后,如果您使用Reporting Services显示信息,我会高度考虑使用Matrix工具进行数据的旋转和求和,因为这正是它的作用。

进一步解释,因为您似乎将使用SSRS。您的矩阵将具有与此类似的数据集:

SELECT
   [week]=DATEPART(ISO_WEEK,ta.enddate),
   ta.id,
   ta.MetalType as GoldorSilver
FROM  table1 ta 
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'

矩阵将具有页眉和页脚,列组将是[周],其中列组总数将在一周内完成总和。行组页脚将在所有周内完成总和。

答案 2 :(得分: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