0

I have a table that is a list of every item in the system. There is a column that says whether the item is a default item or not. In the query I'm going through the items and selecting ones that have a MSDS associated with them, however my query returns multiple items for the same item number because multiple records exist for the item.

So what I want to do is limit the results to just default items. Normally I would just do WHERE itemsrc.itemsrc_default, however not every item has been setup with a default record, so what I want to do is go through the table and if a default record exists for an item than give priority to that item, otherwise if no default record exists, return the first record for that item number.

I'm not sure if I would do this as a subquery in the WHERE clause of the main query or if I should make function that checks for defaults.

2 Answers 2

2

You could use DISTINCT ON

SELECT  DISTINCT ON (ItemID) ItemID, itemsrc_default, Column1, Column2 
FROM    itemsrc
ORDER BY ItemID, itemsrc_default DESC, Column1, Column2;

From the docs:

DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first.

Simple Demo on SQL Fiddle

You can also get the same results using ROW_NUMBER()

SELECT  *
FROM    (   SELECT  ...,
                    ROW_NUMBER() OVER(PARTITION BY ItemID ORDER BY itemsrc_default DESC, SomeCol) AS RowNum
            FROM    itemsrc
        ) i
WHERE   RowNum = 1;

Example using ROW_NUMBER

Sign up to request clarification or add additional context in comments.

Comments

0
SELECT *
FROM itemsrc src
WHERE itemsrc_default = True
OR NOT EXISTS (
    SELECT * FROM itemsrc nx
    WHERE nx.itemId = src.itemID
    AND nx.key_column < src.key_column
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.