SELECT C.CompanyID AS [CompanyID],
C.CompanyName AS [CompanyName],
COALESCE([2019_12_Sales],0) AS [2019_12_Sales],
COALESCE([2019_11_Sales],0) AS [2019_11_Sales],
COALESCE([2019_10_Sales],0) AS [2019_10_Sales],
COALESCE([2019_9_Sales],0) AS [2019_9_Sales],
COALESCE([2019_8_Sales],0) AS [2019_8_Sales],
COALESCE([2019_7_Sales],0) AS [2019_7_Sales],
COALESCE([2019_6_Sales],0) AS [2019_6_Sales],
COALESCE([2019_5_Sales],0) AS [2019_5_Sales],
COALESCE([2019_4_Sales],0) AS [2019_4_Sales],
COALESCE([2019_3_Sales],0) AS [2019_3_Sales],
COALESCE([2019_2_Sales],0) AS [2019_2_Sales],
COALESCE([2019_1_Sales],0) AS [2019_1_Sales]
FROM
Demo_Company C
LEFT OUTER JOIN
(SELECT CompanyID, CONVERT(varchar(4),YEAR(SaleDate)) + '_' + CONVERT(varchar(2),MONTH(SaleDate)) + '_Sales' AS SalePeriod, amount
FROM Demo_CompanySales
WHERE YEAR(SaleDate) = 2019
) AS SourceTable
PIVOT
(
SUM(Amount)
FOR SalePeriod IN (
[2019_12_Sales],
[2019_11_Sales],
[2019_10_Sales],
[2019_9_Sales],
[2019_8_Sales],
[2019_7_Sales],
[2019_6_Sales],
[2019_5_Sales],
[2019_4_Sales],
[2019_3_Sales],
[2019_2_Sales],
[2019_1_Sales]
)
) AS SalesTable
ON C.CompanyID = SalesTable.CompanyID
ORDER BY C.CompanyID
|