日期:2014-05-16 浏览次数:20869 次
Select sum(num) From ( select aid,max(num) as num from ab group by aid)T
------解决方案--------------------
select sum(num) from ab t where not exists (select 1 from ab where aid=t.aid and num>t.num)
and not exists (select 1 from ab where aid=t.aid and num=t.num)
------解决方案--------------------
(不要高估你的汉语表达能力或者我的汉语理解能力)
建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
1. 你的 create table xxx .. 语句
2. 你的 insert into xxx ... 语句
3. 结果是什么样,(并给以简单的算法描述)
4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。
------解决方案--------------------
根据你的需求,我搭建的测试环境:
CREATE TABLE ab(
id INT ,
aid INT,
num INT
) ;
INSERT INTO ab VALUES(1, 1, 10);
INSERT INTO ab VALUES(2, 2, 12);
INSERT INTO ab VALUES(3, 3, 1);
INSERT INTO ab VALUES(4, 1, 12);
INSERT INTO ab VALUES(5, 2, 13);
INSERT INTO ab VALUES(6, 3, 14);
INSERT INTO ab VALUES(7, 4, 20);
INSERT INTO ab VALUES(8, 1, 1);
INSERT INTO ab VALUES(9, 2, 2);
INSERT INTO ab VALUES(10, 3, 18) ;
INSERT INTO ab VALUES(11, 5, 12);
INSERT INTO ab VALUES(12, 2, 13);
SELECT SUM(max_num) FROM (
SELECT aid,MAX(num) AS max_num FROM ab GROUP BY aid
) a ;
结果是:75
------解决方案--------------------
CREATE TABLE ab(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
aid INT,
num INT
) ;
INSERT INTO ab VALUES(1, 1, 10);
INSERT INTO ab VALUES(2, 2, 12);
INSERT INTO ab VALUES(3, 3, 1);
INSERT INTO ab VALUES(4, 1, 12);
INSERT INTO ab VALUES(5, 2, 13);
INSERT INTO ab VALUES(6, 3, 14);
INSERT INTO ab VALUES(7, 4, 20);
INSERT INTO ab VALUES(8, 1, 1);
INSERT INTO ab VALUES(9, 2, 2);
INSERT INTO ab VALUES(10, 3, 18);
INSERT INTO ab VALUES(11, 5, 12);
INSERT INTO ab VALUES(12, 2, 13);
SELECT SUM(NUM) FROM AB A WHERE NOT EXISTS(SELECT 1 FROM AB WHERE (A.AID=AID AND A.NUM<NUM)
OR (A.`aid`=AID AND A.`num`=NUM AND A.`id`<ID)
)