如何加入group by语句

时间:2010-05-26 11:19:37

标签: sql sql-server tsql

我有两张桌子

表A

Custid prodid Amt1
  1      10   200
  2      20   300
  3      10   400
  4      30   300
  5      20   400
  6      30   200

表B

prodid  Amt2
    10   100
    20   200
    30   300

我希望通过prodid汇总所有金额组。谁能给我ansi和Tsql查询?

4 个答案:

答案 0 :(得分:1)

SELECT a.prodid,sum(a.Amt1 + b.Amt2) as AmtSum 
     FROM TableA a JOIN TableB b ON (a.prodid = b.prodid) 
     GROUP BY a.prodid;

答案 1 :(得分:0)

那怎么样? : - )

  

SELECT SUM(a.Amt1),SUM(b.Amt2)
  FROM(表A作为内部联接表B AS b ON   a.prodid = b.prodid)
  GROUP BY a.prodid

答案 2 :(得分:0)

我相信这可以在任何地方使用:

SELECT a.Custid,a.prodid,sum(a.Amt1 + b.Amt2) as AmtSum FROM TableA a JOIN TableB b ON (a.prodid = b.prodid) GROUP BY a.Custid,a.prodid;

答案 3 :(得分:0)

尝试这个...我认为如果某些产品ID不在TABLEB中,它也会起作用

SELECT a.prodid,SUM(a.Amt1),SUM(b.Amt2)
FROM TableA AS a left outer JOIN TableB AS b ON a.prodid = b.prodid
GROUP BY a.prodid