PIVOT和SQL Server 2014中的几个聚合

时间:2016-01-26 19:10:24

标签: sql-server tsql sql-server-2014

我目前的理解是,在以下示例中不可能有多个聚合 - 例如额外的SUM(Measure2):

IF OBJECT_ID('tempdb..#Dim1') IS NOT NULL DROP TABLE #Dim1
IF OBJECT_ID('tempdb..#Dim2') IS NOT NULL DROP TABLE #Dim2
IF OBJECT_ID('tempdb..#Facts') IS NOT NULL DROP TABLE #Facts

CREATE TABLE #Dim1
(
    Id INT IDENTITY(1,1),
    DimName NVARCHAR(100)
)

CREATE TABLE #Dim2
(
    Id INT IDENTITY(1,1),
    DimName NVARCHAR(100)
)

CREATE TABLE #Facts 
(
    Id INT IDENTITY(1,1),
    Dim1Id INT,
    Dim2Id INT,
    Measure1 FLOAT,
    Measure2 FLOAT
)

INSERT INTO #Dim1
    SELECT N'Dim1Name1'
        UNION ALL 
    SELECT N'Dim1Name2'
        UNION ALL 
    SELECT N'Dim1Name3'

INSERT INTO #Dim2
    SELECT N'Dim2Name1'
        UNION ALL 
    SELECT N'Dim2Name2'

INSERT INTO #Facts 
    SELECT 1, 2, 2, 10
        UNION ALL 
    SELECT 1, 2, 10, 3
        UNION ALL 
    SELECT 1, 1, 1, 56
        UNION ALL 
    SELECT 2, 1, 5, 4
        UNION ALL 
    SELECT 2, 2, 4, 4
        UNION ALL 
    SELECT 3, 1, 4, 1
        UNION ALL 
    SELECT 3, 1, 20, 56

;WITH CTE1 AS
(
    SELECT 
        Facts.Measure1,
        Dimensions1.DimName AS DimName1,
        Dimensions2.DimName AS DimName2
    FROM #Facts AS Facts
    INNER JOIN #Dim1 AS Dimensions1 ON Facts.Dim1Id = Dimensions1.Id
    INNER JOIN #Dim2 AS Dimensions2 ON Facts.Dim2Id = Dimensions2.Id
)
SELECT 
    *
FROM CTE1
PIVOT
(
    SUM(Measure1)
    FOR DimName2
    IN([Dim2Name1], [Dim2Name2])
) AS X; 

这是否真的如此,我是否必须使用旧的' MAX CASE'这些方案的方法是什么?

1 个答案:

答案 0 :(得分:0)

这有用吗?

;WITH CTE1 AS
(
    SELECT 
        Facts.Measure1,
        Facts.Measure2,
        Dimensions1.DimName AS DimName1,
        Dimensions2.DimName AS DimName2
    FROM #Facts AS Facts
    INNER JOIN #Dim1 AS Dimensions1 ON Facts.Dim1Id = Dimensions1.Id
    INNER JOIN #Dim2 AS Dimensions2 ON Facts.Dim2Id = Dimensions2.Id
)
SELECT
    DimName1,
    CAST(SUBSTRING(X.[Dim2Name1], 1, 10) AS INT) Dim2Name1Measure1,
    CAST(SUBSTRING(X.[Dim2Name1], 11, 10) AS INT) Dim2Name1Measure2,
    CAST(SUBSTRING(X.[Dim2Name2], 1, 10) AS INT) Dim2Name2Measure1,
    CAST(SUBSTRING(X.[Dim2Name2], 11, 10) AS INT) Dim2Name2Measure2
FROM
(
    SELECT 
        CAST(SUM(Measure1) AS CHAR(10)) + CAST(SUM(Measure2) AS CHAR(10)) AS Combined,
        DimName1,
        DimName2
    FROM CTE1
    GROUP BY
        DimName1,
        DimName2
) S
PIVOT
(
    MAX(Combined)
    FOR DimName2
    IN([Dim2Name1], [Dim2Name2])
) AS X;