2017-09-16 37 views
0

我有一個問題,關於我的班級出勤報告與動態範圍的日期。到目前爲止,我能夠顯示兩個日期之間的日期並將其作爲一個列。我現在的問題是要顯示的數據行。在我的查詢中,如果多個日期的數據插入到我的考勤表中並且具有相同的學生ID,它也會在我的查詢中輸出相同的ID在另一行中。MYSQL SELECT查詢合併表單上的輸出

這裏是我的查詢:

$startDate = date_format(new DateTime($_POST['from']),"Y-m-d"); 
$endDate = date_format(new DateTime($_POST['to']),"Y-m-d"); 
$section = $_POST['section']; 
$subject = $_POST['subject']; 
global $request; 

$step1 = mysqli_query($connect,"SET @sql = NULL;") or die(mysqli_error()); 
$step2 = mysqli_query($connect,"SET SESSION group_concat_max_len = 1000000;") or die(mysqli_error()); 
$query1 = mysqli_query($connect,"SELECT GROUP_CONCAT(DISTINCT 
    CONCAT(
     'COALESCE((CASE WHEN tbl_subjectattendance.Date = ''', 
     date_format(date, '%Y-%m-%d'), 
     ''' THEN tbl_subjectattendance.status END), '''') AS `', 
     date_format(date, '%Y-%m-%d'), '`' 
    ) 
) INTO @sql 
FROM calendar 
where date>='$startDate' 
    and date <='$endDate'") or die(mysqli_error($connect)); 

$step3 = mysqli_query($connect,"SET @sql = CONCAT('SELECT DISTINCT tbl_subjectattendance.student_id, tbl_student.last_name, ', @sql, ' 
      FROM 
       tbl_subjectattendance, tbl_student 
      WHERE 
       tbl_subjectattendance.section_id = ''$section'' 
      AND 
       tbl_subjectattendance.subj_id = ''$subject'' 
      AND 
       tbl_subjectattendance.student_id = tbl_student.student_id')") or die(mysqli_error($connect)); 

$query = mysqli_query($connect,"SELECT @sql;") or die(mysqli_error()); 

while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){ 
    $request = $row['@sql']; 
} 

這是我做的將其輸出到一個HTML表/數據表:

<?php 
    $result = mysqli_query($connect, "$request") or die(mysqli_error($connect)); 
?> 
<table class="table table-hover table-bordered" id="report" style="background-color:white;"> 
    <thead> 
     <tr> 
    <?php 
    $row = mysqli_fetch_assoc($result); 
    foreach ($row as $col => $value) { 
      echo "<th>".$col."</th>"; 
     } 
    ?> 
     </tr> 
    </thead> 
    <tbody> 
<?php 
     mysqli_data_seek($result, 0); 
     while ($row = mysqli_fetch_assoc($result)) { 
?> 
<tr> 
<?php   
     foreach($row as $key => $value){ 
       echo "<td>".$value."</td>"; 
       } 
?> 
</tr> 
<?php } ?> 
</tbody> 
</table> 

這裏是輸出:

enter image description here

因此,您可以看到,每個日期的數據有不同的行數據同一個學生。我想要的是將它們合併成一行。我認爲這與我的查詢或我輸出它的方式有關。我希望有人能幫助我。

回答

0

更新:這是對於將來會遇到同樣問題的人。

我能夠把COALESCE一個MAX函數內解決我的問題。

這就是:

$query1 = mysqli_query($connect,"SELECT GROUP_CONCAT(DISTINCT 
CONCAT(
    'MAX(COALESCE((CASE WHEN tbl_subjectattendance.Date = ''', 
    date_format(date, '%Y-%m-%d'), 
    ''' THEN tbl_subjectattendance.status END), '''')) AS `', 
    date_format(date, '%Y-%m-%d'), '`' 
) 
) INTO @sql 
FROM calendar 
WHERE date>='$startDate' 
AND date <='$endDate'") or die(mysqli_error($connect));