创建数据透视表后汇总SQL Server中的列

时间:2018-12-19 14:22:06

标签: sql-server

数据透视后,我无法汇总表(SQL-Server)中的数字,我将非常感谢您的建议。

如果我在示例中解释问题,更好:

现有表格:

    +-------+-----------+-----------+-------------------+
    |   #   |   $$$$$   |   Fire    |       Water       |
    +-------+-----------+-----------+-------------------+
    |   1   |   5       |       1   |   5               |
    |   1   |   4       |       1   |   5               |
    |   1   |   10      |       1   |   5               |
    |   2   |   3       |       3   |   8               |
    |   2   |   4       |       3   |   8               |
    +-------+-----------+-----------+-------------------+

所需的输出:

+-------+-----------+-----------+-------------------+
|   #   |   $$$$$   |   Fire    |       Water       |
+-------+-----------+-----------+-------------------+
|   1   |   19      |       1   |   5               |
|   2   |   7       |       3   |   8               |
+-------+-----------+-----------+-------------------+

我倾向于认为我已经尝试过使用汇总和分组找到的所有解决方案,但是并没有解决,因此我依靠您。提前致谢。我用来创建表格的代码:

WITH Enerc AS
(
    SELECT  
        a1.[#],
        a1.[$$$$$],
        a2.[cause_of_loss]          
    FROM 
        data1 AS a1
    LEFT JOIN 
        data2 AS a2 ON a1.[id] = a2.[id]
)
SELECT *
FROM Enerc
PIVOT 
    (SUM(gross_claim) FOR [cause_of_loss] IN ([Fire], [Water])) AS PivotTable;

2 个答案:

答案 0 :(得分:2)

无需旋转。您应该通过分组并使用SUM来获得所需的结果:

SELECT  
    a1.[#],
    SUM(a1.[$$$$$]),
    a1.[Fire]
    a1.[Water]  
from data1 as a1
group by  a1.[#],  a1.[Fire], a1.[Water]    

让我展示一个例子:

DECLARE @Hello TABLE
(
    [#] INT,
    [$$$$$] INT,
    [Fire] INT,
    [Water] INT
)

INSERT INTO @Hello
(
    #,
    [$$$$$],
    Fire,
    Water
)
VALUES
(   1, -- # - int
    5, -- $$$$$ - int
    1, -- Fire - int
    5  -- Water - int
    )
, (1, 4, 1, 5)
, (1, 10, 1, 5)
, (2, 3, 3, 8)
, (2, 4, 3, 8)

SELECT 
h.#, 
SUM(h.[$$$$$]),
h.Fire, 
h.Water 
FROM @Hello h
GROUP BY h.#, h.Fire, h.Water

答案 1 :(得分:0)

在数据透视后尝试分组。

 With Enerc as
    (SELECT  
        a1.[#],
        a1.[$$$$$],
        a2.[cause_of_loss]

    from data1 as a1
left join data2 as a2
on a1.[id] = a2.[id]
)
select *
into tmp
from Enerc
PIVOT
(sum(gross_claim) 
FOR [cause_of_loss] in (
[Fire], [Water])) 
as PivotTable


select   [#], sum([$$$$$])as [$$$$$],  Fire,   Water 
from #tmp
group by [#],Fire, Water 

编辑:在权限被拒绝的情况下:

With Enerc as
    (SELECT  
        a1.[#],
        a1.[$$$$$],
        a2.[cause_of_loss]

    from data1 as a1
left join data2 as a2
on a1.[id] = a2.[id]
),phase2 as(
select *
from Enerc
PIVOT
(sum(gross_claim) 
FOR [cause_of_loss] in (
[Fire], [Water])) 
as PivotTable)
select  [#], sum([$$$$$])as [$$$$$],  Fire,   Water  
from phase2
group by [#],Fire, Water