2016-11-10 28 views
0

你好,請幫我以下的問題顯示兩行數據

MySQL數據表是

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 

是possaible在MYSQL PHP中。

+1

簡短的回答,不可能和你的輸出完全一樣 –

+0

這是非常可能的 –

+0

這根本就沒有意義。爲什麼用SNO 1-5保存5x Test1但想要用SNO2顯示Test2?你的結構不要做任何事...... – Twinfriends

回答

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; 
}