Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I hope I've understood you correctly, but a query like this might be what you need (BTW I haven't tested this and I'm not sure about using COUNT - what happens if it counts a number > 1?):</p> <p>(Edit: I have added some test data and results to help clarify the situation also debugged a couple of copy and paste errors.)</p> <p>Basically each left join represents sale item products from a particular group the case statement is the driver for the logic.</p> <p>Test it out and have a play around, the temporary tables at the top will allow you to use your own test data to try out different cases.</p> <p>Also I remmed out the WHERE clause and added a group by so you can see all the test data at a glance...</p> <pre><code>DECLARE @SaleId int DECLARE @tbl_SalesItems AS TABLE(SaleID int, SaleItemCode varchar(10)) DECLARE @tbl_Products AS TABLE(ProductGroup int, ProductCode varchar(10)) INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (1,'Product1') INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (2,'Product2') INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (3,'Product1') INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (3,'Product2') INSERT INTO @tbl_SalesItems(SaleID, SaleItemCode) VALUES (3,'Product3') INSERT INTO @tbl_Products(ProductGroup, ProductCode) VALUES (13, 'Product1') INSERT INTO @tbl_Products(ProductGroup, ProductCode) VALUES (14, 'Product2') INSERT INTO @tbl_Products(ProductGroup, ProductCode) VALUES (16, 'Product3') INSERT INTO @tbl_Products(ProductGroup, ProductCode) VALUES (16, 'Product4') SET @SaleId = 1 SELECT si.SaleId ,CASE WHEN COUNT(pg13.ProductCode) = 1 AND COUNT(pg14.ProductCode) = 0 AND COUNT(pg16.ProductCode) = 0 THEN 1 WHEN COUNT(pg13.ProductCode) = 0 AND COUNT(pg14.ProductCode) = 1 AND COUNT(pg16.ProductCode) = 0 THEN 2 ELSE 0 END AS ATCType FROM @tbl_SalesItems si LEFT JOIN @tbl_Products pg13 ON si.SaleItemCode = pg13.ProductCode AND (pg13.ProductGroup = 13) LEFT JOIN @tbl_Products pg14 ON si.SaleItemCode = pg14.ProductCode AND (pg14.ProductGroup = 14) LEFT JOIN @tbl_Products pg16 ON si.SaleItemCode = pg16.ProductCode AND (pg16.ProductGroup = 16) --WHERE si.SaleId = @SaleId GROUP BY si.SaleId </code></pre> <p><strong>Results:</strong></p> <pre><code>SaleId ATCType 1 1 2 2 3 0 4 2 </code></pre>
    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.
 

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