tags:

views:

57

answers:

2

I have this table

NAME|VALUE|
T   |  A
T   |  NONE
T   |  B
S   |  NONE

where the value NONE is a NULL value in real.


I need to do a query who will return all lines BUT if th name have a value i should ONLY return the line with his value like this in result for the table above:

NAME|VALUE|
T   |  A
T   |  B 
S   |  NONE

Do you know to do such query?

Thanks in advance for your help.

+1  A: 

Is there a max of two values? That is, is only possible to get a single value, "NONE", or one of each. If so, you can do this:

SELECT name, COALESCE(MAX(NULLIF(value, 'NONE'), 'NONE')
FROM <tablename>
GROUP BY name

I believe the following will work for the general case (one or more non-NONE values possible):

SELECT name, value FROM <tablename> WHERE value <> 'NONE'
UNION
SELECT name, value FROM <tablename> WHERE value = 'NONE'
  AND name NOT IN (SELECT name FROM <tablename> WHERE value <> 'NONE')
Matthew Wood
No there's no MAX value as the field value is a text.
mada
@mada: that's quite an important piece of information - you should probably mention that in the question. Otherwise GROUP BY and MAX would be a good solution.
Mark Byers
MAX still works for text fields. In the case where are ONLY two possible values for any one name (non-"NONE" and "NONE") we can take advantage of the fact that MAX removes NULLs from the aggregation, leaving on the single non-NONE value behind. This value is, by definition, the MAX. If only NONE values are found for a particular name, we change the NULL returned by MAX back to the string "NONE" (adding an edit now to cover this case).
Matthew Wood
+1  A: 

Here's one way you could do it:

SELECT T1.NAME, T2.VALUE
FROM (SELECT DISTINCT name FROM Table1) AS T1
LEFT JOIN (SELECT * FROM Table1 WHERE VALUE IS NOT NULL) AS T2
ON T1.NAME = T2.NAME

Results:

S   NULL
T   A
T   B
Mark Byers
mada
@mada: What? I don't understand your comment. What is 'NONE'? Do you mean NULL? The nulls aren't ignored because it is a *LEFT* join, not a join. LEFT joins return NULL if the match fails.
Mark Byers
None mean NULL.
mada
@mada: Then it should work because the join fails on those rows, which causes NULLs in the result, and that is exactly what you want. I've tested it here and it seems to work for me.
Mark Byers