如果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查询完成?
答案 0 :(得分:1)
对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
示例输出:
答案 1 :(得分:0)
听起来每个组只能有一行或两行,其中一行必须为null。使用这些假设,您可以通过简单的查询逃脱。
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
)
答案 2 :(得分:0)
使用此代码:
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