Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to suppress a field in select statement if it is equal to a second field in the same table 3

Status
Not open for further replies.

rradelet

IS-IT--Management
Oct 28, 2003
35
CA
If am trying to run a simple select query from one table:

SELECT FIELD1,FIELD2 FROM TABLEA

FIELD1 FIELD2
Blue Red
Green Green
Yellow Yellow
Orange Purple
Black Black

but if FIELD2 is equal to FIELD I want the result to look like:

FIELD1 FIELD2
Blue Red
Green
Yellow
Orange Purple
Black
 
Hi,
[pre]
SELECT
FIELD1
, case when field1=field2 then '' else field2 end
FROM TABLEA
[/pre]
 
Thank you Skip.

I had been trying to use the case function, but I was little bit out on the exact syntax.
 
Skip's advice will work well. There is another method you can use that is similar.

The NullIf function accepts two parameters. If the parameters are the same value, NULL will be returned, otherwise the first parameter will be returned.

Ex:

Code:
Select NullIf('A', 'A')  -- This returns NULL
Select NullIf('X', 'Y')  -- This returns X

You could use it like this:

Code:
Select Field1,
       NullIf(Field2, Field1) As Field2
From   YourTableNameHere

This differs from Skip's advice in that his will return an empty string, while this will return NULL.

I only mention this because it's another way to accomplish something similar, and it always helps to know more.

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top