title: Compare sales for the current month with the previous month - Functions - T-SQL
body: <p>I have created a SalesMonth function that receives as parameter a month number and a year number and presents a totaled list with the products sold in the month and year passed as parameter. The list shows the following product information: Identifier, Month, Year, Total Sold Quantity, Average Unit Price, Total Discount Granted and Total Value Sold.</p>
  
  <p>Follow the code below:</p>
  
  <pre><code>CREATE FUNCTION SalesMonth (@month int, @year int)
  RETURNS TABLE
  AS
  RETURN (
      SELECT
          AdventureWorks.Sales.SalesOrderDetail.ProductID,
          MONTH(AdventureWorks.Sales.SalesOrderHeader.OrderDate) as 'Mes',
          YEAR(AdventureWorks.Sales.SalesOrderHeader.OrderDate) as 'Ano',
          SUM(AdventureWorks.Sales.SalesOrderDetail.OrderQty) as 'Quantidade Total Vendida',
          AVG(AdventureWorks.Sales.SalesOrderDetail.UnitPrice) as 'Preco Unitario Médio',
          SUM(AdventureWorks.Sales.SalesOrderDetail.UnitPriceDiscount) as 'Desconto Total',
          SUM(AdventureWorks.Sales.SalesOrderDetail.LineTotal) as 'Valor Total Vendido'
      FROM
          AdventureWorks.Sales.SalesOrderDetail
      INNER JOIN
          AdventureWorks.Sales.SalesOrderHeader
      ON
          AdventureWorks.Sales.SalesOrderHeader.SalesOrderID = AdventureWorks.Sales.SalesOrderDetail.SalesOrderID
      WHERE 
          MONTH(AdventureWorks.Sales.SalesOrderHeader.OrderDate) = @month
              AND
          YEAR(AdventureWorks.Sales.SalesOrderHeader.OrderDate) = @year
      GROUP BY
              AdventureWorks.Sales.SalesOrderDetail.ProductID,
              MONTH(AdventureWorks.Sales.SalesOrderHeader.OrderDate),
              YEAR(AdventureWorks.Sales.SalesOrderHeader.OrderDate)
  )
  </code></pre>
  
  <p>Now I need to compare which items had a growth in sales compared to the previous month. I thought about doing something like:</p>
  
  <pre><code>SELECT * 
  FROM SalesMonth(10, 2001) 
  WHERE SumPrice &gt; (SELECT SumPrice FROM SalesMonth(9, 2001))
  </code></pre>
  
  <p>I know this is a gross error, but I could not think of anything like it. Would anyone have any idea of ​​similar query for this problem?</p>