1

I have a table below.

Name          Product
---------------------
Value          2002
HigherLimit    *
HigherLimit    2002
LowerLimit     *

I need a select statement to return distinct(Name) with the following condition.

If a Product is 2002 then return '2002' else return '*'

Here is the expected result

Name          Product
---------------------
Value          2002
HigherLimit    2002
LowerLimit     *

Any help would be greatly appreciated.

Thanks Niju

3
  • Is it distinct name and product, if not is it if any of the names have a product use 2002, if not use *? And what is your DB server? Commented Jan 9, 2013 at 2:47
  • what rdbms you are using? MySQL? SQLServer? Oracle? etc.... Commented Jan 9, 2013 at 2:48
  • Only distinct name, distinct product is inserted per name. IT is SQL 2008 R2 Commented Jan 9, 2013 at 2:49

1 Answer 1

2

Since 2002 will evaluate as greater than *, you can simply use a MAX() aggregate grouped by Name:

SELECT
  Name,
  MAX(Product) AS Product
FROM yourtable
/* WHERE Product IN ('2002', '*') -- if necessary */
GROUP BY Name
ORDER BY Product DESC

http://sqlfiddle.com/#!2/8da48/2

However, if your real table has more values than just 2002 or *, and you want to return the 2002 values rather than the greatest number, use a CASE to separate out the value you want (2002) and return all others as *. The MAX() aggregate is applied in the same way though:

SELECT
  Name,
  /* Force *all* values not 2002 to be `*` */
  MAX(CASE WHEN Product = '2002' THEN Product ELSE '*' END) AS Product
FROM yourtable
GROUP BY Name
ORDER BY Product DESC

http://sqlfiddle.com/#!2/f03af/2

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

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.