簡體   English   中英

帶有where子句和sum值的Mysql數據透視表

[英]Mysql pivot table with where clause and sum values

SELECT * FROM ( 
select student_id, class_id,  
       sum(number*(1-abs(sign(subject-1)))) as sub1,  
       sum(number*(1-abs(sign(subject-2)))) as sub2,  
       sum(number*(1-abs(sign(subject-3)))) as sub3,  
       sum(number*(1-abs(sign(subject-4)))) as sub4,  
       sum(number*(1-abs(sign(subject-5)))) as sub5,  
       sum(number*(1-abs(sign(subject-6)))) as sub6  
from result GROUP BY student_id,class_id) m 
where class_id = '7'

它的查詢工作正常。 但是如果主題值為null,則所有學生記錄都不會顯示在該主題中。 我需要多發燒。

我不知道是否有任何方法直接使用mysql,但我可以建議你使用PHP

$sql = mysql_query("SELECT m.* FROM (  
select student_id, class_id,   
       sum(number*(1-abs(sign(subject-1)))) as sub1,   
       sum(number*(1-abs(sign(subject-2)))) as sub2,   
       sum(number*(1-abs(sign(subject-3)))) as sub3,   
       sum(number*(1-abs(sign(subject-4)))) as sub4,   
       sum(number*(1-abs(sign(subject-5)))) as sub5,   
       sum(number*(1-abs(sign(subject-6)))) as sub6   
from result GROUP BY student_id,class_id) m  
where m.class_id = '7'");

$row = mysql_fetch_array($sql);
$sum = 0;
for($i = 1; $i < count($row); $i++) {
    $sum += isset($row['sub' . $i]) ? $row['sub' . $i] : 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM