SQL Server - использование функции PIVOT - PullRequest
0 голосов
/ 27 сентября 2018

Мне нужна помощь, чтобы выяснить, как добавить функцию PIVOT в этот SQL-запрос для этого вопроса.

Найти процент заявок, обработанных по состоянию (статусу), в пределах их SLA, за месяц, за последние 12 месяцев.

Вот что у меня есть до сих пор ...

SELECT cs.ERRetroResponseStatusId
    , DATENAME(MONTH, c.CreatedDate) [Month]
    , SUM(CASE
            WHEN ERRetroResponseStatusId = 1 and (DATEDIFF(HOUR, c.CreatedDate, GETDATE()))<24 THEN 1 
        WHEN ERRetroResponseStatusId = 3 and (DATEDIFF(DAY, c.CreatedDate, GETDATE()))<45 THEN 1 
        ELSE 0 END) AS CountOfGroupedStatusIDs
    , COUNT(cs.ERRetroResponseStatusId) AS TotalAmountOfClaimsInStatus
    , ROUND(100.00 * COUNT(cs.ERRetroResponseStatusId) / SUM(COUNT(*)) OVER(),2) AS [Percentage]
--convert(decimal(18,2),x) 
FROM ERRetroClaimResponse cs
    INNER JOIN ERRetroState s ON cs.ERRetroResponseStatusId = s.Id
    LEFT JOIN ERRetroClaim c ON c.Id = cs.ERRetroClaimId
WHERE cs.CreatedDate BETWEEN DATEADD(MONTH, -12, GETDATE()) AND GETDATE() 
and cs.ERRetroResponseStatusId in (1,3)
GROUP BY cs.ERRetroResponseStatusId, DATENAME(MONTH, c.CreatedDate)
Id   ** ClaimID ** StatusID **      CreatedDate        ** CreatedBy
===========================================================================
1174 **   977   **    1     ** 2018-06-01 18:01:31.387 **     1
---------------------------------------------------------------------------
1175 **   978   **    1     ** 2018-06-01 18:01:31.387 **     1
---------------------------------------------------------------------------
1176 **   979   **    1     ** 2018-06-01 18:01:31.387 **     1
---------------------------------------------------------------------------
1177 **   980   **    1     ** 2018-06-01 18:01:31.403 **     1
---------------------------------------------------------------------------
1178 **   981   **    1     ** 2018-06-01 18:01:31.403 **     1
---------------------------------------------------------------------------

1 Ответ

0 голосов
/ 27 сентября 2018

Этот запрос будет преобразовывать ваши идентификаторы состояния в имена столбцов, а месяцы указываются в качестве значений строк.

;WITH AggData AS
(
    SELECT cs.ERRetroResponseStatusId
        , DATENAME(MONTH, c.CreatedDate) AS [Month]
        , SUM(CASE
                WHEN ERRetroResponseStatusId = 1 and (DATEDIFF(HOUR, c.CreatedDate, GETDATE()))<24 THEN 1 
            WHEN ERRetroResponseStatusId = 3 and (DATEDIFF(DAY, c.CreatedDate, GETDATE()))<45 THEN 1 
            ELSE 0 END) AS CountOfGroupedStatusIDs
        , COUNT(cs.ERRetroResponseStatusId) AS TotalAmountOfClaimsInStatus
    FROM ERRetroClaimResponse cs
    INNER JOIN ERRetroState s ON cs.ERRetroResponseStatusId = s.Id
    LEFT JOIN ERRetroClaim c ON c.Id = cs.ERRetroClaimId
    WHERE cs.CreatedDate BETWEEN DATEADD(MONTH, -12, GETDATE()) AND GETDATE() 
        AND cs.ERRetroResponseStatusId in (1,3)
    GROUP BY cs.ERRetroResponseStatusId, DATENAME(MONTH, c.CreatedDate)
)
SELECT 
    [Month]
    , [1] AS 'For ERRetroResponseStatusId = 1'
    , [3] AS 'For ERRetroResponseStatusId = 3'
FROM
(
    SELECT 
        ERRetroResponseStatusId
        ,[Month]
        , ROUND((CountOfGroupedStatusIDs / TotalAmountOfClaimsInStatus) * 100.00, 2) AS [Percentage]
    FROM AggData
) AS SourceTable
PIVOT
(
    MAX([Percentage])
    FOR ERRetroResponseStatusId IN ([1],[3])
) AS PivotTable

И этот запрос будет преобразовывать месяцы в имена столбцов.

;WITH AggData AS
(
    SELECT cs.ERRetroResponseStatusId
        , DATENAME(MONTH, c.CreatedDate) AS [Month]
        , SUM(CASE
                WHEN ERRetroResponseStatusId = 1 and (DATEDIFF(HOUR, c.CreatedDate, GETDATE()))<24 THEN 1 
            WHEN ERRetroResponseStatusId = 3 and (DATEDIFF(DAY, c.CreatedDate, GETDATE()))<45 THEN 1 
            ELSE 0 END) AS CountOfGroupedStatusIDs
        , COUNT(cs.ERRetroResponseStatusId) AS TotalAmountOfClaimsInStatus
    FROM ERRetroClaimResponse cs
    INNER JOIN ERRetroState s ON cs.ERRetroResponseStatusId = s.Id
    LEFT JOIN ERRetroClaim c ON c.Id = cs.ERRetroClaimId
    WHERE cs.CreatedDate BETWEEN DATEADD(MONTH, -12, GETDATE()) AND GETDATE() 
        AND cs.ERRetroResponseStatusId in (1,3)
    GROUP BY cs.ERRetroResponseStatusId, DATENAME(MONTH, c.CreatedDate)
)
SELECT 
    ERRetroResponseStatusId
    ,[January]
    ,[February]
    ,[March]
    ,[April]
    ,[May]
    ,[June]
    ,[July]
    ,[August]
    ,[September]
    ,[October]
    ,[November]
    ,[December]
FROM
(
    SELECT 
        ERRetroResponseStatusId
        ,[Month]
        , ROUND((CountOfGroupedStatusIDs / TotalAmountOfClaimsInStatus) * 100.00, 2) AS [Percentage]
    FROM AggData
) AS SourceTable
PIVOT
(
    MAX([Percentage])
    FOR [Month] IN ([January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])
) AS PivotTable
...