MySQL JOIN查询中的GROUP BY

时间:2014-10-22 05:40:46

标签: mysql join group-by

有两张桌子。第一个存储每个用户的费用

+----+----+----+
| id |uid |fee |
+----+----+----+
| 1  |P001|100 |
+----+----+----+
| 2  |P002|200 |
+----+----+----+
| 3  |P003|250 |
+----+----+----+
| 4  |P004|100 |
+----+----+----+
| 5  |P001|200 |
+----+----+----+
| 6  |P002|200 |
+----+----+----+
| 7  |P003|250 |
+----+----+----+
| 8  |P004|100 |
+----+----+----+

第二个存储用户分类

+----+-----+
|uid |class|
+----+-----+
|P001| 1   |
+----+-----+
|P002| 1   |
+----+-----+
|P003| 2   |
+----+-----+
|P004| 3   |
+----+-----+

我希望按照以下类别显示他们的总和

1 - 700
2 - 500
3 - 200

我该如何编写这个SQL查询?提前谢谢。

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT class, SUM(fee)
FROM table1 t1

LEFT JOIN table2 t2
ON t1.uid = t2.uid

GROUP BY class

答案 1 :(得分:1)

试试这个

SELECT a.class, SUM(b.fee)
FROM user_classification a
INNER JOIN user_fees b
ON a.uid = b.uid
GROUP BY a.class
ORDER BY a.class ASC

答案 2 :(得分:1)

假设第一个表tab1和second1是tab2

select t2.class,sum(t1.fee) from tab2 t2 inner join tab1 t1 on t2.uid=t1.uid 
group by t2.class

答案 3 :(得分:1)

SELECT     COUNT(*) AS Expr28, SInv_D.fTransUnitPrice AS fTransUnitPrice, SInv_D.fExtended AS Expr2, SInv_D.fTransQty * SInv_D.fTransUnitPrice AS fTransUnitPrice, 
                      SInv.cMode AS cMode, SInv.cInvoicNum AS cInvoicNum, SInv.dOperaDate AS dOperaDate, SInv_D.cMode AS Expr9, SInv_D.cInvoicNum AS Expr10, 
                      SInv_D.cItCode AS cItCode, SInv_D.cItName AS cItName, SInv_D.cTransUnit AS cTransUnit, SUM(SInv_D.fTransQty) AS fTransQty, SInv.cMode AS Expr4, 
                      SInv.cInvoicNum AS Expr16, SInv_D.cItCode AS Expr15, SInv_D.fTransUnitPrice AS Expr19, SInv.dIssueDate AS Expr20, WareDef.cCode AS Expr21, 
                      WareDef.cName1 AS Expr22, item.cUnitR AS Expr24, item.cName1 AS Expr25, item.fCostSTDR AS Expr26, SInv.cWare1 AS Expr27, item.cCode AS cCode, I.Expr999, 
                      I.cItCode AS Expr1
FROM         SInv LEFT OUTER JOIN
                      WareDef ON SInv.cWare1 = WareDef.cCode LEFT OUTER JOIN
                      SInv_D ON SInv.cInvoicNum = SInv_D.cInvoicNum AND SInv.dIssueDate = SInv_D.dIssueDate LEFT OUTER JOIN
                      item ON SInv_D.cItCode = item.cCode INNER JOIN
                          (SELECT     SUM(fTransQty) AS Expr999, cItCode
                             FROM         dbo.sinv_D
                             GROUP BY sinv_D.cItCode) I ON I.cItCode = SInv_D.cItCode
WHERE     (SInv.dIssueDate BETWEEN 20130102 AND 20130109) AND (SInv.cWare1 = '003') AND (SInv.cMode = '122') AND (SInv_D.cMode = '122')
GROUP BY SInv_D.cItCode, SInv_D.fTransUnitPrice, SInv_D.fExtended, SInv_D.fTransQty, SInv.cMode, SInv.cInvoicNum, SInv.dOperaDate, SInv_D.cMode, SInv_D.cInvoicNum, 
                      SInv_D.cItName, SInv_D.cTransUnit, SInv.dIssueDate, WareDef.cCode, WareDef.cName1, item.cUnitR, item.cName1, item.fCostSTDR, SInv.cWare1, item.cCode, 
                      I.Expr999, I.cItCode