表1:
序号  姓名   年龄
1     张三   20
2     李里   23
3     王五   13
4     马六   18
5    .....表2:
序号  姓名   配偶
1     张三   李四
2     李四   张三
3     王五  (空)
4    (空)  马六
5     .....现在要做以下操作,如果表2中:
序号  姓名   配偶
1     张三   李四
2     李四   张三
是这样的一个结构,就是姓名和配偶都对应有名字,就到表1中去查询出张三和李四的年龄总和我用的语句是:
select a.姓名,a.配偶, b.年龄+c.年龄 as 年龄总和 from 表2 a
left join 表1 b on a.姓名=b.姓名
left join 表1 c on a.配偶=c.姓名
where 姓名 is not null and 配偶 is not null
但是查出来的结果为:
姓名  配偶  年龄总和  
张三  李四  43
李四  张三  43有重复了,我想把这重复的记录去掉,请 高手指点,怎么把这个重复的去掉!

解决方案 »

  1.   

    create table A(序号 int, 姓名 varchar(10), 年龄 int)
    insert A select 1,     '张三',   20
    union all select 2,     '李四',   23
    union all select 3,     '王五',   13
    union all select 4,     '马六',   18create table B(序号 int, 姓名 varchar(10), 配偶 varchar(10))
    insert B select  1,     '张三',   '李四'
    union all select 2,     '李四',   '张三'
    union all select 3,     '王五',   NULL
    union all select 4,     null,   '马六'select *,
    年龄总和=(select sum(年龄) from A where 姓名=tmp.姓名 or 姓名=tmp.配偶)
    from B as tmp
    where exists(select 1 from B where 配偶=tmp.姓名 and 序号<tmp.序号)--result
    序号          姓名         配偶         年龄总和        
    ----------- ---------- ---------- ----------- 
    2           李四         张三         43(1 row(s) affected)