2016-10-01 81 views
1

如果id只有一条记录,并且选择非空值,则选择空值为空的记录id有多个记录如果id只有一条记录,并且当id有多个记录时选择非空值

下面是示例示例。

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查询来完成?

+1

如果有多个记录,但是它们全都为空,你想要什么? – Bohemian

+0

或多个记录不为空? – dsz

回答

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 

输出示例:

enter image description here

使用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 

输出示例:

enter image description here

+0

感谢您的回应。但即时得到低于错误它是计数或Row_Number消息102,级别15,状态1,行3 '订单'附近的语法不正确。 – user2514925

+0

你正在使用哪个版本的sql server? –

+0

查看更新的脚本。 –

0

这听起来像你只能每组有一个或两排,其中一人必须有空。使用这些假设,您可以通过简单的查询获得。

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 
) 
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 
相关问题