合并怎么取舍? 空的字段用第二条的去代替,非空的呢? 是否合并规则是这样的?name,area 相同的合并,其他字段保留第一条非空的记录?

解决方案 »

  1.   

    对的!  只有空的字段用下一条name,area相同的记录代替,非空的字段保留注:name,area相同的记录 id 不一定相邻, 
        也就是说,有可能一个id 是1, 另一个id是10
        需要先找出 name,area相同的  然后再合并不知道我解释清楚了么?
      

  2.   

    select *
    ,birthday=(select top 1 birthday from tb where name=a.name and area=a.area and isnull(birthday,'')<>'')
    ,sex=(select top 1 sex from tb where name=a.name and area=a.area and isnull(sex,'')<>'')
    ,email=(select top 1 email from tb where name=a.name and area=a.area and isnull(email,'')<>'')
    ,Memo=(select top 1 Memo from tb where name=a.name and area=a.area and isnull(Memo,'')<>'')
    from(
    select id=min(id),name,area
    from tb 
    group by name,area
    )a
      

  3.   

    而且 又可能name,area相同的记录会是3个, 但是合并的原则一样
      

  4.   

    select min(id),name,area,max(birthday),max(sex),max(email),max(memo)
    from tb 
    group by name,erea
      

  5.   

    zjcxc(邹建) :
      还有更优化的方法么? 如果不以第一条为准,以记录中birthday 日期大的为准呢?
    如:
    id   name   area     birthday    sex       email           memo
    1    张三   北京    1980-01-01                            自由人
    2    张三   北京    1981-01-01    男                       自由
    10   张三   北京    1979-01-01    男     [email protected]        自由2结果:
    id   name   area     birthday    sex        email         memo
    1    张三   北京    1981-01-01    男      [email protected]      自由
      

  6.   

    如果合并的处理没有严格要求是第一个非空的,建议用 victorycyz(中海) 的这种合并方式,这样的效率高
      

  7.   

    --如果以 birthday 日期大的为准 ,则就这样写就行了select a.* from tb a
    where not exists(
    select * from tb where name=a.name and area=a.area and birthday>a.birthday)
      

  8.   


    --或者是这样
    select a.* 
    from tb a,(
    select birthday=max(birthday),name,area 
    from tb group by name,area
    )b where a.name=b.name and a.area=b.area and a.birthday=b.birthday
      

  9.   

    --如果还要考虑 birthday 最大的会重复,则:
    select a.* from tb a
    where not exists(
    select * from tb 
    where name=a.name and area=a.area 
    and(birthday>a.birthday or birthday=a.birthday and id>a.id))--或者是这样
    select a.* 
    from tb a,(
    select id=max(id) --假设id为主键
    from tb a,(
    select birthday=max(birthday),name,area 
    from tb group by name,area
    )b where a.name=b.name and a.area=b.area and a.birthday=b.birthday
    group by a.name,a.area,a.birthday
    )b where a.id=b.id