Этот запрос будет преобразовывать ваши идентификаторы состояния в имена столбцов, а месяцы указываются в качестве значений строк.
;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