当前位置: 代码迷 >> Sql Server >> 字段是ip,ip1,iP2,ip1是null时ip2或许为null,也可能不是,如图T1
  详细解决方案

字段是ip,ip1,iP2,ip1是null时ip2或许为null,也可能不是,如图T1

热度:72   发布时间:2016-04-24 09:02:41.0
字段是ip,ip1,iP2,ip1是null时ip2可能为null,也可能不是,如图T1

这是t1
下图是效果图t2


select c.ip,ip1,ip2 from (
select a.ip as ip,a.ip1,b.ip2 from 
(
select ip,ip1 
from test4 where (ip2 is null and ip1 is not null) or(ip1 is not null and ip2 is not null)
)  a
inner join 
(select ip,ip2 
from test4 where (ip1 is null and ip2 is not null) or(ip1 is not null and ip2 is not null)
)  b on a.ip=b.ip) c
想使用上面的语句实现这种效果,但是生产环境的test4每天有几十万条数据,这样运行的话会不会影响速度,有没有大神有更加好的语句呀!!!!
------解决思路----------------------
DECLARE @tbT TABLE 
(
    IP TINYINT
,   IP1 VARCHAR(5)
,   IP2  VARCHAR(5)
);

INSERT INTO @tbT VALUES
    (1,'a',NULL)
,   (1,NULL,'AAA')
,    (2,'a',NULL)
,   (2,NULL,'BBB')
,    (3,'c',NULL)
,   (3,NULL,'CCC')
,    (4,'d',NULL)
,   (4,NULL,'DDD')
,    (5,'e',NULL)
,   (5,NULL,'EEE')
;

SELECT IP,MAX(IP1) IP1 ,MAX(IP2) IP2 
FROM   @tbT
GROUP BY IP
/*
IP   IP1   IP2
---- ----- -----
1    a     AAA
2    a     BBB
3    c     CCC
4    d     DDD
5    e     EEE
*/

------解决思路----------------------
用楼上的就可以了。
  相关解决方案