原表身份 姓名 国家
小贩 小王 中国
杀手 小王 中国
司机 小李 中国
保镖 小李 中国
厨师 小赵 中国
教师 小赵 中国
形象大使 甜甜 日本
av 甜甜 日本
卖肉 美美 日本
首相 美美 日本
小贩 小王 日本
杀手 小王 日本求表
姓名 身份1 身份2 国家
小王 小贩 杀手 中国
小李 司机 保镖 中国
小赵 厨师 教师 中国
甜甜 形象大使 av 日本
美美 卖肉 首相 日本
小王 小贩 杀手 日本
请大家看看,有什么好方法,谢谢!

解决方案 »

  1.   

    建表时加上了id
    select b.name,b.身份1,c.身份2,b.gj from(
    select name,gj,sf 身份1 from a3 where id in(
    select MIN(id) from a3
    group by name,gj)) b
    inner join 
    (
    select name,gj,sf 身份2 from a3 where id in(
    select Max(id) from a3
    group by name,gj)) c on b.name = c.name and b.gj=c.gj
      

  2.   

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[a3]') AND type in (N'U'))
    DROP TABLE [dbo].a3
    GO
    create table a3(
    id int ,
    sf varchar(30),
    name varchar(30),
    gj varchar(30))insert into a3
    select  1  , '小贩', '小王', '中国' union 
    select  2  , '杀手', '小王', '中国' union 
    select  3  , '司机', '小李', '中国' union 
    select  4  , '保镖', '小李', '中国' union 
    select  5  , '厨师', '小赵', '中国' union 
    select  6  , '教师', '小赵', '中国' union 
    select  7  , '形象大使', '甜甜', '日本' union 
    select  9  , 'av', '甜甜', '日本' union 
    select  10  , '卖肉', '美美', '日本' union 
    select  11  , '首相', '美美', '日本' union 
    select  12  , '小贩', '小王', '日本' union 
    select  13  , '杀手', '小王', '日本' 
    select * from a3
      

  3.   

    select b.Name,b.ID as 身份1,c.ID as 身份2,b.Guo from(
     select Name,Guo,ID from Table_1 where ID in(
     select MIN(ID) from Table_1
     group by Name,Guo)) b
     inner join 
     (
     select Name,Guo,ID  from Table_1 where ID in(
     select Max(ID) from Table_1
     group by Name,Guo)) c on b.Name = c.Name and b.Guo=c.Guo 
      

  4.   

    select b.Name,b.ID as 身份1,c.ID as 身份2,b.Guo from(
     select Name,Guo,ID from Table_1 where ID in(
     select MIN(ID) from Table_1
     group by Name,Guo)) b
     inner join 
     (
     select Name,Guo,ID  from Table_1 where ID in(
     select Max(ID) from Table_1
     group by Name,Guo)) c on b.Name = c.Name and b.Guo=c.Guo