表tab1
ID,Name
1,上海
2,北京表tab2
ID,Num
1,100
2,300
1,300现在分组统计tab2 
select ID,sum(num) from tab2 group by ID
1,400
2,300上面即显示ID,不能直接返回ID对应的名称
要显示
上海,400
北京,300
sql如何写

解决方案 »

  1.   

    select  T.name ,M.sm
    from tab1 T,
    (select ID,sum(num) sm from tab2 group by ID)M
    WHERE T.ID=M.ID
      

  2.   

    select
      a.name,b.num
    from
      tab1 a 
    join
      (select ID,sum(num) sm from tab2 group by ID) b
    on
      a.id=b.id
      
      

  3.   

    select ID,sum(num) from tab2 group by ID
    1,400
    2,300
    --你都到这步了?还不会写?
    两表关联一下就行了。
    select m.name,sum(n.num) from tab1 m , tab2 n where m.id = n.id group by m.name
      

  4.   

    select table1.name ,sum(table2.num) from table1 inner join table2 on table1.id = table2.id group by table1.name