Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Assuming that your tables <strong>StockIn</strong> and <strong>StockOut</strong> have a column <strong>Amount</strong>, instead the question is senseless.</p> <p>So, the ugly and the simple query is:</p> <pre><code>SELECT BeginningStockIn IsNull(BeginningStockIn.Amount, 0)-IsNull(BeginningStockOut.Amount, 0) BeginningStock, IsNull(PeriodStockIn.Amount, 0) StockIn, IsNull(PeriodStockOut.Amount, 0) StockOut, IsNull(BeginningStockIn.Amount, 0)-IsNull(BeginningStockOut.Amount, 0)+IsNull(PeriodStockIn.Amount, 0)-IsNull(PeriodStockOut.Amount, 0) StockBalance FROM Product LEFT JOIN ( SELECT SUM(Amount) Amount, Product_Code FROM StockIn WHERE StockIn_Date &lt; @StartDate ) BeginningStockIn ON BeginningStockIn.Product_Code = Product.Product_Code LEFT JOIN ( SELECT SUM(Amount) Amount, Product_Code FROM StockOut WHERE StockOut_Date &lt; @StartDate ) BeginningStockOut ON BeginningStockOut.Product_Code = Product.Product_Code LEFT JOIN ( SELECT SUM(Amount) Amount, Product_Code FROM StockIn WHERE StockIn_Date &gt;= @StartDate AND StockIn_Date &lt; @EndDate ) PeriodStockIn ON PeriodStockIn .Product_Code = Product.Product_Code LEFT JOIN ( SELECT SUM(Amount) Amount, Product_Code FROM StockOut WHERE StockOut_Date &gt;= @StartDate AND StockOut_Date &lt; @EndDate ) PeriodStockOut ON PeriodStockOut.Product_Code = Product.Product_Code </code></pre> <p>And <strong>the answer</strong> - to create the stored procedure you have to use <code>CREATE PROCEDURE</code> statement as described <a href="http://msdn.microsoft.com/en-us/library/ms187926.aspx" rel="nofollow">here</a></p> <pre><code>CREATE PROC YourProcName @StartDate datetime, @EndDate datetime AS BEGIN SET NOCOUNT ON; the query END </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload