![](/img/trans.png)
[英]Only select one record if there are more than one of only certain same value of record
[英]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
如果 id 只有一条记录,我想得到一条为 null 的记录,当 id 有多条记录时,选择 not null 值
下面是示例示例。
Id Field1 Field2
1 Null 34
1 Yes 52
2 Null 56
3 No 46
和输出
Id Field1 Field2
1 Yes 52
2 Null 56
3 No 46
如何使用 sql 查询来完成?
对 2008+ 版本的 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
示例输出:
对 2005 版本使用以下查询。
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
示例输出:
听起来每组只能有一两行,其中之一必须为空。 使用这些假设,您可以通过一个简单的查询逃脱。
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
它还做了一个小假设,即Field2
不可为空。 实际上它比这更微妙,但如果你需要它,有一个解决方法。
使用exists
和子查询的解决方案是另一种选择:
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
)
使用此代码:
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
结果:
ID Field1 Field2
----------- ---------- -----------
1 Yes 52
2 NULL 56
3 No 46
(3 row(s) affected)
下面的代码也得到相同的结果:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.