简体   繁体   中英

Select a record having null if the id has only one record and select not null value when the id has more than one record

I want to get a record having null if the id has only one record and select not null value when the id has more than one record

Below is example sample.

Id Field1 Field2
1  Null    34
1  Yes     52
2  Null    56
3  No      46

and output

Id Field1 Field2
1  Yes    52
2  Null   56
3  No     46

How it can be done using sql query?

Use the below query for 2008+ versions of sql server.

 ;with cte_1
  As
   ( select *, count(1) over (partition by id order by id) Cnt
     From YourTable)
   Select Id,Field1,Field2
   From Cte_1
   Where Field1 is null and Cnt=1
   UNION
   Select Id,Field1,Field2
   From YourTable 
   Where field1 is not null

Sample output :

在此处输入图片说明

Use the below query for 2005 version.

SELECT t.Id,Field1,Field2
FROM #T t
   JOIN   (select ID, count(ID) CntId
           From #t
           GROUP BY ID
           HAVING COUNT(ID)=1)t1 on t.ID=t1.ID
 WHERE t.Field1 is  null

    UNION 

 SELECT Id,Field1,Field2
 FROM #T 
 WHERE Field1 is NOT NULL
 ORDER BY ID

Sample output :

在此处输入图片说明

It sounds like you can only have one or two rows per group and one of them must have the null. Using those assumptions you can get away with a simple query.

select
    Id,
    min(Field1) as Field1,
    coalesce(min(case when Field1 is not null then Field2 end), min(Field2)) as Field2
from T
group by Id

It also makes a minor assumption that Field2 isn't nullable. Actually it's a little more subtle than that but there's a workaround if you need it.

A solution using exists and a subquery is another option:

select * from T t1
where Field is not null or not exists (
    select 1 from T t2
    where t2.Id = t1.Id and t2.Field is not null
)

Use this code:

Select Distinct ID,
(Select Max(Field1) From Table1 Where ID=Tbl1.ID) as Field1,
(Select Max(Field1) From Table1 Where ID=Tbl1.ID) as Field2
From Table1 as Tbl1

Result:

ID          Field1     Field2
----------- ---------- -----------
1           Yes        52
2           NULL       56
3           No         46

(3 row(s) affected)

Also below code get same result:

Select Distinct ID,
(Select Top 1 Field1 From Table1 Where ID=Tbl1.ID  Order By Field1 Desc) as Field1,
(Select Top 1 Field2 From Table1 Where ID=Tbl1.ID Order BY field1 Desc) as Field2
From Table1 as Tbl1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM