你好请帮助我解决以下问题
Mysql DATA表是
Sno Name Subject Marks
1 Test1 Sub1 20
2 Test1 Sub2 20
3 Test1 Sub3 20
4 Test1 Sub4 20
5 Test1 Sub5 20
6 Test2 Sub1 30
7 Test2 Sub2 30
8 Test2 Sub3 30
9 Test2 Sub4 30
10 Test2 Sub5 30
11 Test3 Sub1 40
12 Test3 Sub2 40
13 Test3 Sub3 40
14 Test3 Sub4 40
15 Test3 Sub5 40
我希望像这样显示
Sno Name Marks
1 Test1 100
Sub1 20
Sub2 20
Sub3 20
Sub4 20
Sub5 20
2 Test2 150
Sub1 30
Sub2 30
Sub3 30
Sub4 30
Sub5 30
3 Test3 200
Sub1 40
Sub2 40
Sub3 40
Sub4 40
Sub5 40
可以在MYSQL PHP中使用。
答案 0 :(得分:1)
两种方法
1)找到所有唯一名称和标记总和
Select Name AS Heading, SUM(Marks) AS Total FROM table GROUP BY Name
然后遍历结果并查询与名称
匹配的所有记录Select * from table WHERE Name = $result['Heading']
2)获取所有记录,然后遍历结果以对它们进行分组
Select * from table WHERE
$headings = [];
$children = [];
foreach($allrecords as $result)
{
if (!in_array($result['Name'], $headings)
{
$headings[$result['Name']]['Name'] = $result['Name'];
}
if (isset($headings[$result['Name']]['Marks']))
{
$headings[$result['Name']]['Marks'] += $result['Marks']
}
else
{
$headings[$result['Name']]['Marks'] = $result['Marks']
}
$children[$result['Name']][] = $result;
}