开发者

How to join with group by statement

开发者 https://www.devze.com 2022-12-31 21:49 出处:网络
I have two tables TableA Custid prodid Amt1 110200 220300 310400 430300 520400 630200 TableB prodidAmt2 10100 2020开发者_开发问答0

I have two tables

TableA

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

TableB

prodid  Amt2
    10   100
    20   20开发者_开发问答0
    30   300

and I want to sum of all amount group by prodid. Can anyone give me both ansi and Tsql queries?


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;


What about that? :-)

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


I believe this will work anywhere:

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;


try this... I think it will also work if some product id not in 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
0

精彩评论

暂无评论...
验证码 换一张
取 消