I’m trying to query a few tables in our db that contains product data. It is a MSSQL 2005 database. The problem is its returning multiple rows for one product when I need it to only produce one row per product. Blow is the query and results I’m using.
SELECT ProductItem.sku, ProductItem.title, ProductItem.short_desc, ProductItem.long_desc, ProductItem.active, ProductItem.product_item_id,
ProductCategory.category_desc, ProductCategoryMap.product_id, ProductCategory.active AS activecat, Product.adwords_label,
ProductItem.item_price, ProductItem.sale_price
FROM Product INNER JOIN
ProductCategoryMap INNER JOIN
ProductCategory ON ProductCategoryMap.product_category_id = ProductCategory.product_category_id ON
Product.product_id = ProductCategoryMap.product_id FULL OUTER JOIN
ProductItem ON Product.product_key = ProductItem.sku
WHERE (ProductItem.active = 1) AND (ProductCategory.active = 1)
This returns the following results:
I know the problem occurs because the product resides in multiple categories, but really I don’t need every category its in, just one of them. So ideally just one product for every row returned
I can’t figure out how to make my query achieve that though.
Can anyone help me out please?
At first glance, take category columns out and add DISTINCT. You’ve asked for “category” so you can get all categories.
Also:
I’ve tweaked it for clarity and added an aggregate to get one category
Edit: you can tidy it more with APPLY which will also deal with no categories if changed to OUTER APPLY