有表A
id   name_id   score
1      a         10
2      a         10
2      a         10
3      b         20
4      c         20
4      c         20
5      d         30
我想要的结果为
name    scoreA   score B
a         30         20
b         20         20
c         40         20
d         30         30
就是按照name_id分组,然后计算score的总和,但是要分两次,一次是去重,另外一次不去重求和
这个是我根据实际情况简单化的表,实际情况是数据量有20万条,name有100个不重复,这个表是子查询的结果,是根据三个表联立得到的结果,三个表的数据是20万,40万,40万得到这个结果花了0.5秒的时间,如果在写这么一句子查询,那花费的时间会成倍
不知道有什么其他的方法

解决方案 »

  1.   

    select C.name_id,C.scoreA,D.scoreB
    from (
    select name_id,sum(score) as scoreA
    from A
    group by name_id
    )C,(
    select name_id,sum(score)
    from A A1
    group by name_id,id
    )D
    where C.name_id=D.name_id
      

  2.   

    SELECT name_id,sum(score),(select sum(score) from tt1 where a.name_id=name_id) from tt1 a where not exists(select 1 from tt1 where a.id=id and a.id1>id1)  group by name_id
    ;
    自增字段ID1
      

  3.   

    select name_id,sum(score) as scoreA,
    (select sum(score) from (select distinct id,name_id,score from 表A where name_id=t.name_id)) as scoreB
    from 表A t
    group by name_id注意索引的创建。
    另外提问时请贴出你自己的语句,而不是让别人重新分析,可能给出的结果与你自己的完全相同。
    贴出你的 explain 和 show index.
    贴出你实际的表,否则别人根本无法帮你。
    问题说明越详细,回答也会越准确!参见如何提问。(提问的智慧