문제

Ok here goes:

I have a table with id ( can be duplicate but not NULL ) and value ( can be duplicate and NULL )

id      value
-----   -----
1       red
1       red
1       (null)
2       blue
2       blue
3       (null)

So how do I return the id's and value's of all the records that have a value, but if a null value is also found don't include it in the result set.

So the return would be

id      value
-----   -----
2       blue

as id 1 and 3 have a value of (null) in one or more of the results

도움이 되었습니까?

해결책

It's a typical "select where not exists"-type query with many ways to write the answer, for example:

Using a LEFT JOIN / WHERE ... IS NULL:

SELECT DISTINCT T1.id, T1.value
FROM your_table T1
LEFT JOIN your_table T2
ON T1.id = T2.id AND T2.value IS NULL
WHERE T2.id IS NULL

Using NOT IN:

SELECT DISTINCT id, value
FROM your_table
WHERE id NOT IN
(
    SELECT DISTINCT id
    FROM your_table
    WHERE value IS NULL
)

Using NOT EXISTS:

SELECT DISTINCT id, value
FROM your_table
WHERE NOT EXISTS
(
    SELECT NULL
    FROM your_table T1
    WHERE your_table.id = T1.id AND T1.value IS NULL
)

다른 팁

select t1.id, t1.value
from MyTable t1
left outer join MyTable t2 on t1.id = t2.id and t2.value is null
where t2.id is null
group by t1.id, t1.value
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top