开发者

Select distinct multiple field without NULL

I have a table with Value ID and Value

--------------
| id | value |
--------------
|  1 |  NULL |
--------------
|  1 |     A |
----开发者_高级运维----------
|  2 |  NULL |
--------------
|  2 |  NULL |
--------------
|  3 |     B |
--------------
|  3 |     B |
--------------
|  3 |     B |
--------------

I need to select distinct id and corresponding value from the table. When selecting the Id should be unique and if it is having multiple values in the value field it should retrieve only not NULL values

So the result should be like below.

--------------
| id | value |    
--------------
|  1 |     A |
--------------
|  2 |  NULL |
--------------    
|  3 |     B |
--------------

How to achieve this? using SQL server 2005


You can use a regular GROUP BY.

The GROUP BY will

  • eliminate the NULL value from 1 because other values are present.
  • retain the NULL value for 2 because it only has NULL values.

SQL Statement

SELECT  id
        , MIN(value)
FROM    YourTable
GROUP BY
        id

Test script

;WITH q (id, value) AS (
    SELECT 1, NULL
    UNION ALL SELECT 1, 'A'
    UNION ALL SELECT 2, NULL
    UNION ALL SELECT 2, NULL
    UNION ALL SELECT 3, 'B'
    UNION ALL SELECT 3, 'B'
    UNION ALL SELECT 3, 'B'
)
SELECT  id
        , MIN(value)
FROM    q       
GROUP BY
        id


It's a bit convoluted, but it should do the trick:

select distinct x.id, x.value
  from table x
 where x.value is not null 
    or not exists 
       (select y.id 
          from table y 
         where y.id = x.id 
           and y.value is not null)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜