Primero creas una funcion:
Código SQL:
Ver originalIF OBJECT_ID (N'dbo.ProductResultByMonth', N'FN') IS NOT NULL
DROP FUNCTION dbo.ProductResultByMonth;
GO
CREATE FUNCTION dbo.ProductResultByMonth(@ProductId INT, @YEAR INT, @MONTH INT)
RETURNS DECIMAL
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @RESULT DECIMAL;
SELECT
@RESULT = SUM([ORDER Details].UnitPrice * [ORDER Details].Quantity)
FROM
Products
INNER JOIN
[ORDER Details]
ON
[ORDER Details].ProductID = Products.ProductID
INNER JOIN
Orders
ON
[ORDER Details].OrderID = Orders.OrderID
WHERE
Products.ProductID = @ProductId AND
YEAR(Orders.OrderDate) = @YEAR AND
MONTH(Orders.OrderDate) = @MONTH
RETURN(ISNULL(@RESULT,0));
END;
GO
Luego para lograr el formato que requieres utilizas la funcion:
Código SQL:
Ver originalDECLARE @YEAR INT
SET @YEAR = 1997
SELECT
ProductName,
dbo.ProductResultByMonth(ProductID, @YEAR, 1) Enero,
dbo.ProductResultByMonth(ProductID, @YEAR, 2) Febrero,
dbo.ProductResultByMonth(ProductID, @YEAR, 3) Marzo,
dbo.ProductResultByMonth(ProductID, @YEAR, 4) Abril,
dbo.ProductResultByMonth(ProductID, @YEAR, 5) Mayo,
dbo.ProductResultByMonth(ProductID, @YEAR, 6) Junio,
dbo.ProductResultByMonth(ProductID, @YEAR, 7) Julio,
dbo.ProductResultByMonth(ProductID, @YEAR, 8) Agosto,
dbo.ProductResultByMonth(ProductID, @YEAR, 9) Septiembre,
dbo.ProductResultByMonth(ProductID, @YEAR, 10) Octubre,
dbo.ProductResultByMonth(ProductID, @YEAR, 11) Noviembre,
dbo.ProductResultByMonth(ProductID, @YEAR, 12) Diciembre
FROM
Products (nolock)
Suerte