我有一个存储报告名称的MySQL表,每个条目我有一个表格,我有每个主题的标记。
Reports
+------------+----------+
| S.No. |ReportName|
+------------+----------+
| 1 | Report1 |
| 2 | Report2 |
+------------+----------+
Report1
+------------+----------+
| Subject | Marks |
+------------+----------+
| Maths | 78 |
| English | 99 |
+------------+----------+
Report2
+------------+----------+
| Subject | Marks |
+------------+----------+
| Maths | 80 |
| English | 99 |
+------------+----------+
现在,我希望将每个报告中的标记总和作为表格。我可以为一张桌子而不是为所有桌子做这件事。
对于一张表,它是:
SELECT (SUM(marks)) AS Total FROM `Report1`
预期:
+------------+----------+
| ReportName | Marks |
+------------+----------+
| Report1 | 177 |
| Report2 | 179 |
+------------+----------+
答案 0 :(得分:3)
你可以尝试一下
使用UNION
合并Report1
和Report2
SELECT 'Report1' AS ReportName, SUM(Marks) AS Marks
FROM Report1
UNION ALL
SELECT 'Report2' AS ReportName, SUM(Marks) AS Marks
FROM Report2
修改强>
表格Rport1
和Rport2
的数据格式相同。
我建议您可以将表格Report1
和Report2
合并为InfoReport
InfoReport
可join
Reports
ReportID
+------------+----------+----------+
| Subject | Marks | ReportID |
+------------+----------+----------+
| Maths | 78 | 1 |
| English | 99 | 1 |
| Maths | 80 | 2 |
| English | 99 | 2 |
+------------+----------+----------+
像这样的新查询。
SELECT t1.ReportName as 'ReportName',
SUM(T.Marks) as Marks
FROM InfoReport AS T
INNER JOIN Reports as T1 ON T.ReportID = T1.SNO
GROUP BY t1.ReportName
答案 1 :(得分:0)
Aggregating functions in MySQL必须与group by一起使用。
在您的情况下,您需要将其添加到
SELECT (SUM(marks)) AS Total FROM `Report1`
GROUP BY whatever_column
此外,在您的示例中,您可能希望加入"标记"其他报告的列,因此您应该考虑使用JOIN或UNION查询。