Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Select Query - problem pivoting rows into columns
    primarykey
    data
    text
    <p>I have three tables in an SQL 2005 database, that I need to query and display on one row. The tables are:</p> <pre><code>MasterStock StockID, Description 1, Plate 2, Bowl ShopStock ShopID, StockID, StockLevel 1,1,6 2,1,0 3,1,0 4,1,10 Sales StockId, ShopId, SoldQuantity, transDate 1, 1, 1, 5/1/2011 1,2,1, 5/1/2011 </code></pre> <p>I need to get them to show one row: </p> <p>StockID, Description, 1 Sales, 1 Stock, 2 Sales, 2 Stock, 3 Sales,…</p> <p>I have managed to get what somewhere with the query below:</p> <pre><code>SELECT MasterStock.StockID, MasterStock.Description, SUM(CASE WHEN sales.shopid = 1 THEN sales.Soldquantity ELSE 0 END) AS [1 Sold], MAX(CASE WHEN shopstock.shopid = 1 THEN shopstock.stockLevel ELSE 0 END) AS [1 Stock], SUM(CASE WHEN sales.shopid = 2 THEN sales.Soldquantity ELSE 0 END) AS [2 Sold], MAX(CASE WHEN shopstock.shopid = 2 THEN shopstock.stockLevel ELSE 0 END) AS [2 Stock], SUM(CASE WHEN sales.shopid = 3 THEN sales.Soldquantity ELSE 0 END) AS [3 Sold], MAX(CASE WHEN shopstock.shopid = 3 THEN shopstock.stockLevel ELSE 0 END) AS [3 Stock], SUM(CASE WHEN sales.shopid = 4 THEN sales.Soldquantity ELSE 0 END) AS [4 Sold], MAX(CASE WHEN shopstock.shopid = 4 THEN shopstock.stockLevel ELSE 0 END) AS [4 Stock] FROM ShopStock INNER JOIN Sales ON ShopStock.StockID = Sales.StockID AND ShopStock.shopID = Sales.ShopID INNER JOIN MasterStock ON ShopStock.StockID = MasterStock.StockID WHERE (sales.transdate &gt; 1/1/2010) GROUP BY MasterStock.StockID, MasterStock.Description </code></pre> <p>However, if there are no sales for the product it doesn’t show any stock levels. If I remove the shopID join on shopstock and sales it shows the stock levels, but reports inaccurate sales - multiplies by four (one for each shopstock record?).</p> <p>I know I’m missing something here, but I’m not getting anywhere! Any help would be greatly received.</p>
    singulars
    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.
    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