日期:2014-05-18  浏览次数:20493 次

取最全项的问题
之前一个问题没有大神回答,我自己想出的办法现在有个新问题。


有一表
ID name var1 var2 var3
1 A null A2 A3
2 B B2 null
3 B B1 B2 null
4 C null C2 C3
5 C C1 null
6 C C1 C2 C3

我需要选择出如下项,简单的说就是补全信息删除重复的项

ID name var1 var2 var3
1 A null A2 A3
3 B B1 B2 null
6 C C1 C2 C3

如何用SQL实现?

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test](
[ID] int,
[name] varchar(1),
[var1] varchar(2),
[var2] varchar(2),
[var3] varchar(2)
)
insert [test]
select 1,'A',null,'A2','A3' union all
select 2,'B','B2',null,null union all
select 3,'B','B1','B2',null union all
select 4,'C',null,'C2','C3' union all
select 5,'C','C1',null,null union all
select 6,'C','C1','C2','C3'

with t
as(
select *,
   case when [var1] is null then 1 else 0 end+
   case when [var2] is null then 1 else 0 end+
   case when [var3] is null then 1 else 0 end as totals
from test
)
select [ID],[name],[var1],[var2],[var3] from t a
where totals=(select MIN(totals) from t b where a.name=b.name)

/*
ID    name    var1    var2    var3
1    A    NULL    A2    A3
3    B    B1    B2    NULL
6    C    C1    C2    C3
*/