日期:2014-05-18 浏览次数:20441 次
/* 两个表结构一样, Id int LoginName varchar(50) num int Grade int 数据如下: t1 1 zhangsan 1 1 2 lisi 4 1 3 wangwu 7 4 4 xiaoming 3 3 t2 1 zhangsan 8 1 2 lisi 9 1 3 wangwu 8 4 4 xiaoming 8 3 怎么可以查询成下面的结果 根据去除重复的loginname获取sum(num) 1 zhangsan 9 1 2 lisi 13 1 3 wangwu 15 4 4 xiaoming 11 3 */
select a.id,a.loginname,a.num+b.num as num a.grade from t1 a inner join t2 b on a.id=b.id
------解决方案--------------------
SELECT ID,LOGINNAME,SUM(NUM),GRADE
FROM
(SELECT * FROM A
UNION ALL
SELECT * FROM B)
T
GROUP BY ID,LOGINNAME,GRADE
------解决方案--------------------
select LoginName,sum(num) from (select LoginName,num from A union all select LoginName,num from B)t group by LoginName
------解决方案--------------------
select LoginName,sum(num) from (select LoginName,num from A union all select LoginName,num from B)t group by LoginName